@ExceptionHandler的顺序

You*_*sef 10 java spring spring-mvc

@ControllerAdvice用来处理我的所有app异常:

@ControllerAdvice
public class ExceptionHandlingController {

  @ExceptionHandler({UnauthorizedException.class})
  public String unauthorizedException()  {
        .........
  }


  @ExceptionHandler({UnauthorizedAjaxException.class})
  @ResponseBody
  public void unauthorizedAjaxException()  {
        .........
  }

  @ExceptionHandler({Exception.class})
  public String globalException(){
        .........
  }


}
Run Code Online (Sandbox Code Playgroud)

在我的代码中的某个地方,我做到了 throw new UnauthorizedException();

   @Around("@annotation(Authenticated)")
   public Object profilingAuthentication(ProceedingJoinPoint pjp) throws Throwable  {

       HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

       if( request.getSession().getAttribute("idContact") == null ) {
            if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) )
                throw new UnauthorizedAjaxException();
            throw new UnauthorizedException();
       } 
       return pjp.proceed();
   }
Run Code Online (Sandbox Code Playgroud)

但遗憾的是,Spring MVC似乎通过使用最通用的case(Exception)而不是更具体的case(UnauthorizedException例如)来随机行动.有时他会选择正确的!

订单如何运作?并且有什么方法可以指定订单吗?

UnauthorizedException 是一个自定义的例外

public class UnauthorizedException extends Exception {

    public UnauthorizedException(){
        super();
    }

    public UnauthorizedException(String message){
        super(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

我发现它不是rondom的顺序,实际上抛出的方法UnauthorizedException正常但其他方法没有!

@Authenticated
@RequestMapping(value="/favoris") 
public String favoris(ModelMap model, HttpServletRequest request) 
      throws UnauthorizedException {
    ....
}

@Authenticated
@RequestMapping(value="/follow") 
public String follow(ModelMap model, HttpServletRequest request) {
    .....
}
Run Code Online (Sandbox Code Playgroud)

所以我必须throws UnauthorizedException手动添加或有一些其他解决方案?

dev*_*per 0

只要您的项目中有一个控制器建议类,就没有顺序/优先级。但如果你有多个controlleradvice类,你可以设置Order。但在这里,在您的情况下,该顺序不适用,因为两个异常的处理方式不同(即 UnauthorizedException 和 Exception)。

好处是,Spring 会自动找到相应的自定义 Exception 类(如果有,否则为泛型 Exception)并调用相应的方法。

有关 Spring 控制器建议和异常处理的更多信息,请参阅: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc