首页 > 解决方案 > 在两个不同的 @RestController 类中有两个完全相同的 @ExceptionHandler 是不好的做法吗?

问题描述

我有两个 @RestController 类,@RequestMapping("/persons")并且@RequestMapping("/person")它们都可以抛出 PersonAccessException ,这是一个自定义异常。并且由@ExceptionHandler 处理未来还会有更多@RestControllers 可能会抛出此异常,就像在不同的地方一次又一次地编写相同的方法是不行的我不确定是否可以复制并将这个完全相同的异常处理程序粘贴到不同的休息控制器中。

我想知道是否有办法编写一次并从不同的类中使用它,就像普通方法一样。

标签: spring-mvcexceptionspring-restcontroller

解决方案


在两个不同的 @RestController 类中有两个完全相同的 @ExceptionHandler 是不好的做法吗?

-> 这只是避免代码重复和提高可重用性的问题。

Spring 提供了一种定义全局异常处理程序的方法,该处理程序将应用于应用程序中的所有控制器(Web 应用程序上下文)。

我们可以使用@ControllerAdvice注解来定义将处理全局异常的类。带有注释的类@ControllerAdvice可以显式声明为 Spring bean 或通过类路径扫描自动检测

欲了解更多信息控制器建议

@ExceptionHandle我们可以使用注解定义特定于异常的异常处理程序(方法) 。带有注释的方法@ExceptionHandle将在多个 @Controller 类之间共享。

更多ExceptionHandler

适用于 Web 应用程序上下文中所有 @Controller 类的全局异常处理程序示例,

    /**
     * <p>This class is to demonstrate global exception handling in spring mvc.</p>
     * <p>This class is declared under *.web package, so it will be detected by dispatcher servlet and will be part of web application context created by dispatcher servlet</p>
     * <br/> It make more sese to declare these classes as a part of web app context and not part of root context because, we do not want these classes to be able to get injected into root context beans.
     * <br/>
     * This class can handle exceptions thrown from <br/>
     *</t> 1. All controllers in application. <br/>
     *</t> 2. All interceptors in applications.
     * 
     *
     */
    @ControllerAdvice // We can us attributes of this annotation to limit which controllers this exception handler advise should apply/advise. If we we do not specify, it will be applied to all controllers in web application context.
    public class GlobalExceptionHandler {

        @ResponseStatus(code = HttpStatus.NOT_FOUND)
        @ExceptionHandler(SpittleNotFoundException.class)
        public ModelAndView handleSpittleNotFoundException(SpittleNotFoundException exception) {
            // all code in this is exactly similar to request handling code in controller
            ModelAndView modelAndView = new ModelAndView("errors/notFound");
            modelAndView.addObject("errorMessage", exception.getMessage());
            return modelAndView;
        }

        @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
        @ExceptionHandler(Throwable.class)
        public String handleGenericException(Throwable exception) {
            return "errors/internalServerError";
        }
    }

Spring 文档链接,

  1. 控制器建议
  2. 异常处理程序

推荐阅读