0

Lets say I'm using @ExceptionHandler in my application.

If I define :

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public boolean generic(Exception e) {
        return e;
    }

    @ExceptionHandler(value =MyException.class)
    public boolean myException(MyException e) {
        return e;
    }
}

Il my controller throws a MyException, will the generic exception handler be triggered too or only the best match with for the exception will be executed (here the MyException handler) ?

Akah
  • 1,890
  • 20
  • 28
  • 1
    This may help you : https://stackoverflow.com/questions/19498378/setting-precedence-of-multiple-controlleradvice-exceptionhandlers – Thoomas Aug 11 '17 at 13:50
  • Yes, thank you ! The "When an exception occurs, the ExceptionHandlerExceptionResolver will iterate through these ExceptionHandlerMethodResolver and use the first one that can handle the exception." part was exactly what I needed. – Akah Aug 11 '17 at 13:53
  • And you can order them with `@Order` if you need so. – Thoomas Aug 11 '17 at 13:58

1 Answers1

2

The exception handler will try to find the specific exception(MyException) handler firstly, if not it will try to find the generic exception(Exception).

so for your example, when controller throw MyException, the handler will invoke the MyException handler.

An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if the annotation itself does not narrow the exception types through its {@link #value()}. Request and/or response objects (Servlet API or Portlet API).

reference: https://github.com/spring-projects/spring-framework/blob/5f4d1a4628513ab34098fa3f92ba03aa20fc4204/spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java#L33

chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • Ok, so you say that only one Handler will be triggered : the one with the best match. – Akah Aug 11 '17 at 13:50