【问题标题】:Spring-boot Rest : Use ControllerAdvice but keep default handlersSpring-boot Rest:使用 ControllerAdvice 但保留默认处理程序
【发布时间】:2020-01-20 15:19:29
【问题描述】:

我的基本需求是捕获用户定义的异常并返回通用响应。为此,我将@ControllerAdvice 与@ExceptionHandler 一起使用。请参阅下面的示例

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler  {

    @ExceptionHandler(PersonNotFoundException.class)
    public void handleBadPostalCode(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid person Id");
    }

    @ExceptionHandler(Exception.class)
    public void handleDefault(Exception e, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Unknown error happened");
    }
}

PersonNotFoundException 按预期处理。但是其他异常默认处理程序消失了,只返回没有正文的 Http 代码。显然,这是扩展 ResponseEntityExceptionHandler 时的预期行为。 我可以覆盖其他默认异常,但这并不理想。 使用通用的 Exception.class 处理程序将迫使我为所有这些返回一个 HTTP 代码。

所以我正在寻找一种方法来在 ControllerAdvice 或类似中全局处理我自己的异常,而不必覆盖默认异常处理程序

谢谢

【问题讨论】:

    标签: spring rest spring-boot controller-advice


    【解决方案1】:

    处理它的最快和最干净的方法就是在你的异常类上使用@ResponseStatus

     @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
     public class OrderNotFoundException extends RuntimeException {
         // ...
     }
    

    还需要扩展ResponseEntityExceptionHandler 吗?海事组织不是。您只能使用@ControllerAdvice(或@RestControllerAdvice)和@ExceptionHandler来处理它

    此外,您可以直接在方法中返回您的响应,而无需注入 HttpServletResponse 并调用 send() 方法。查看this 指南。

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 1970-01-01
      • 2016-03-25
      • 2020-01-17
      • 1970-01-01
      • 2020-11-27
      • 2019-07-17
      • 2016-12-09
      相关资源
      最近更新 更多