使用多个@ControllerAdvice 类

Kle*_*ota 2 spring exception spring-mvc

我最近开始使用一个@ControllerAdvice类来管理我的 Spring 项目中的异常。我目前的实现是这样的:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) throw e;
        return new ModelAndView("error/5xx", "exception", e);
    }

}
Run Code Online (Sandbox Code Playgroud)

我的下一步应该是处理更多的异常,但为此我正在考虑使用多个类@ControllerAdvice,一个用于 http 状态代码。我的目标是让我的控制器处理表单提交的方法为我的一些自定义状态页面重定向用户(我为每组一个 - 1xx、2xx、3xx、4xx、5xx)。

该方法具有与此类似的结构:

@RequestMapping(value="cadastra")
@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
public String cadastra(Model model) throws InstantiationException, IllegalAccessException {
    model.addAttribute("command", this.entity.newInstance());
    return "private/cadastrar";
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我这是否是一个好方法,并给出一些关于如何实现我的控制器方法来完成我想要的东西的提示?

Dou*_*oug 5

您可以有多个@ControllerAdvice类来处理不同的异常。

但是,因为您正在处理Exception.class上的GlobalDefaultExceptionHandler,所以任何异常都可能被它吞掉。

我解决这个问题的方法是添加@Order( value = Ordered.LOWEST_PRECEDENCE ) 我的一般异常处理程序和@Order( value = Ordered.HIGHEST_PRECEDENCE )其他异常处理程序。