假设我在应用程序中使用@ExceptionHandler。
如果我定义:
@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;
}
}
如果我的 Controller 抛出MyException,通用异常处理程序是否也会被触发,或者仅执行与异常最匹配的异常处理程序(此处为MyException处理程序) ?
最佳答案
异常处理程序将首先尝试查找特定异常(MyException
)处理程序,如果没有的话将尝试查找通用异常(Exception
)。
因此,对于您的示例,当 Controller 抛出
MyException
时,处理程序将调用MyException
处理程序。
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).
关于java - Spring @ExceptionHandler 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636696/