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

Is it bad practice to have two exact same @ExceptionHandler in two different @RestController classes?

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

我想知道是否可以像正常方法一样只编写一次并从不同的 类 中使用它。

Is it bad practice to have two exact same @ExceptionHandler in two different @RestController classes?

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

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

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

更多信息ControllerAdvice

我们可以使用 @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. Controller Advice
  2. Exceptions Handlers