Spring-boot Rest:使用 ControllerAdvice 但保留默认处理程序

Spring-boot Rest : Use ControllerAdvice but keep default handlers

我的基本需求是捕获用户定义的异常和 return 通用响应。为此,我使用了@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 代码被 returned。显然,这是扩展 ResponseEntityExceptionHandler 时的预期行为。 我可以覆盖其他默认异常,但这并不理想。 使用通用 Exception.class 处理程序将迫使我为所有这些处理程序 return 一个 HTTP 代码。

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

谢谢

处理它的最快和最干净的方法就是在您的异常 class:

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

还有扩展ResponseEntityExceptionHandler的必要吗?海事组织不是。您只能使用 @ControllerAdvice(或 @RestControllerAdvice)和 @ExceptionHandler

来处理它

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