【问题标题】:Custom exception handler for status NotFound状态 NotFound 的自定义异常处理程序
【发布时间】:2020-10-10 11:24:55
【问题描述】:

我想为 Spring Boot 的状态 NotFoundException 实现自定义异常处理程序:

@ExceptionHandler({ AccessDeniedException.class, NotFoundException.class })
public ResponseEntity<ErrorResponseDTO> accessDeniedExceptionHandler(final AccessDeniedException ex) {
    ......
}

我找不到NotFoundException 的正确导入方式你知道什么例外吗?对于这种情况,什么是正确的导入方式?

【问题讨论】:

    标签: java spring spring-boot exception


    【解决方案1】:

    我同意@Michiel 的观点,方法参数(AccessDeniedException ex)应该是以下类的父类:

    1. AccessDeniedException
    2. NotFoundException

    试试这个

    @ExceptionHandler({ AccessDeniedException.class, NotFoundException.class })
    public ResponseEntity<ErrorResponseDTO> accessDeniedExceptionHandler(final **Exception** ex) {
        ......
    }
    

    我用过@ControllerAdvice 之类的

    @ControllerAdvice
    public class GlobalControllerExceptionHandler {
    @ExceptionHandler({BadRequestException.class, IllegalArgumentException.class, MaxUploadSizeExceededException.class})
        @ResponseBody
        public ResponseEntity<ErrorResponse> handleBadRequestException(Exception exception, WebRequest request) {
            String message = StringUtils.isEmpty(exception.getMessage()) ? properties.getGeneralMessages().get("fail") : exception.getMessage();
            if (message.contains(";"))
                message = message.substring(0, message.indexOf(";"));
            return getResponseEntity(message, null);
        }
    }
    

    【讨论】:

      【解决方案2】:

      NoHandlerFoundException 添加异常处理程序:

      @ExceptionHandler(NoHandlerFoundException.class)
      public ResponseEntity<ErrorResponseDto> handle(NoHandlerFoundException e) {
          // ...
      }
      

      或者让您的控制器建议扩展 ResponseEntityExceptionHandler 并覆盖 handleNoHandlerFoundException 方法。

      顺便说一句,您的代码 sn-p 为两个不同的异常声明了一个处理程序,而方法参数 final AccessDeniedException ex 明确地期望 AccessDeniedException 类型的异常。我建议要么声明多个处理程序方法,要么将参数概括为 Exception

      【讨论】:

        猜你喜欢
        • 2018-12-07
        • 1970-01-01
        • 2011-07-13
        • 2015-10-18
        • 2023-03-04
        • 1970-01-01
        • 2015-12-05
        • 1970-01-01
        • 2019-02-25
        相关资源
        最近更新 更多