【问题标题】:Generic exception handler prevents specific exception being handled通用异常处理程序可防止处理特定异常
【发布时间】:2019-04-13 18:37:54
【问题描述】:

我有一个 Spring Boot 应用程序,我在那里处理异常。我现在有两种异常处理方法:

@ControllerAdvice
@RestController
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public final BaseResponse<GenericException> handleGenericExceptions(Exception ex, HttpServletRequest request) {
        ....
        return response;
    }

    @ExceptionHandler(MyCustomException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public final BaseResponse<MyCustomException> handleMyCustomException(MyCustomException ex, HttpServletRequest request) {
        ....
        return response;
    }
}

在某些时候,我抛出了一个 MyCustomException 异常,但是当我调试时,我发现它是由 handleGenericExceptions 方法处理的。如果我删除了handleGenericExceptions 方法,那么它由handleMyCustomException 消息处理。

我希望 MyCustomException 由 handleMyCustomException 方法处理,所有其他异常由 handleGenericExceptions 方法处理。 MyCustomException 类扩展 Throwable。这里有什么问题?

谢谢。

【问题讨论】:

    标签: spring spring-boot exception


    【解决方案1】:

    我找到了解决方案,但我现在不知道为什么会这样。

    MyCustomException 类正在扩展 Throwable,我将其更改为扩展 RunTimeException。现在它按预期工作了。

    【讨论】:

      【解决方案2】:

      我没有50个repuatations,所以我在这里回答,希望它有意义。

      Throwable 类有两个重要的子类,Error 和 Exception。您的 MyCustomException 扩展 Throwable。在 spring 中,如果你的代码 throws 扩展了 Throwable ,Spring 默认会将其装饰为 IllegalStateException!我在spring4.3源代码中看到了这一点,如果你想证明这一点,你添加@ExceptionHandler({IllegalStateException})并使你的MyCustomException未修改,这个方法会捕获它!

      以上证据在 org.springframework.web.method.support.InvocableHandlerMethod#doInvoke。

      顺便说一句,我们通常通过 extends RuntimeException 抛出 Exception ,为什么要抛出 Throwable 。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-04
        相关资源
        最近更新 更多