Giving this controller
@GetMapping("/test")
@ResponseBody
public String test() {
if (!false) {
throw new IllegalArgumentException();
}
return "blank";
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleException(Exception e) {
return "Exception handler";
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public String handleIllegalException(IllegalArgumentException e) {
return "IllegalArgumentException handler";
}
Both ExceptionHandler match the IllegalArgumentException
because it's a child of Exception
class.
When I reach /test
endpoint, the method handleIllegalException
is called. If I throw a NullPointerException
, the method handleException
is called.
How does spring knows that it should execute the handleIllegalException
method and not the handleException
method ? How does it manage the priority when multiple ExceptionHandler match an Exception ?
(I thought the order or the ExceptionHandler declarations was important, but even if I declare handleIllegalException
before handleException
, the result is the same)
@Order(Ordered.HIGHEST_PRECEDENCE)
– Cooley@Order
, and thehandleIllegalException
method is called, why not thehandleException
method ? Spring seems to manage the order by itself when no Order is specified... – Marinelli@Order
annotation. It doesn't give any explanation about the default order when multipleExceptionHandler
match an Exception – Marinelli