Issue
I have several entities in a Spring Boot project, and for each of them I've written an exception class like so:
public class Item1NotFoundException extends RuntimeException{
Item1NotFoundException(Long id) {
super("Cannot find Item1 with ID " + id);
}
}
public class Item2NotFoundException extends RuntimeException{
Item1NotFoundException(Long id) {
super("Cannot find Item2 with ID " + id);
}
}
To go along with these exceptions, I've also written corresponding advice classes:
@ControllerAdvice
public class Item1NotFoundAdvice {
@ResponseBody
@ExceptionHandler(Item1NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String item1NotFoundHandler(Item1NotFoundException ex) {
return ex.getMessage();
}
}
And I've written an almost identical class for Item2NotFoundAdvice
. As you can see, this code is highly redundant, and I was wondering what the best way to handle that is. Can I make a generic class for NotFound exceptions and corresponding advice classes to avoid redundant code? I'm not totally sure how I would go about that so any advice is appreciated.
Thanks in advance.
Solution
The @ExceptionHandler
annotation can receive an array of Class<? extends Throwable>
Just do:
@ExceptionHandler({ Item1NotFoundException.class, Item2NotFoundException.class })
Both exceptions will be handled by the same method.
Of course, you'll need to create a super type to handle both of these properly. Maybe a NotFoundException
and then extend it from Item1NotFoundException
and Item2NotFoundException
, then, you can just do
@ExceptionHandler({ NotFoundException.class })
Answered By - Matheus Cirillo
Answer Checked By - Clifford M. (JavaFixing Volunteer)