【发布时间】:2018-02-10 20:07:42
【问题描述】:
给这个控制器
@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";
}
两个 ExceptionHandler 都与 IllegalArgumentException 匹配,因为它是 Exception 类的子类。
当我到达/test 端点时,方法handleIllegalException 被调用。如果我抛出NullPointerException,则调用handleException 方法。
spring 怎么知道它应该执行handleIllegalException 方法而不是handleException 方法?当多个 ExceptionHandler 匹配一个 Exception 时,它如何管理优先级?
(我认为顺序或ExceptionHandler声明很重要,但即使我在handleException之前声明handleIllegalException,结果也是一样的)
【问题讨论】:
-
有注解
@Order(Ordered.HIGHEST_PRECEDENCE) -
是的,但在我的示例中,我没有设置任何
@Order,并且调用了handleIllegalException方法,为什么不调用handleException方法?当没有指定 Order 时,Spring 似乎会自行管理订单... -
@surya 你的链接没有回答我的问题,它谈到了
@Order注释。当多个ExceptionHandler匹配一个异常时,它没有给出关于默认顺序的任何解释 -
使用两类@controlleradvice 可以保证订单
标签: java spring spring-mvc exceptionhandler