通用异常处理程序可防止处理特定异常

问题描述 投票:0回答:2

我有一个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消息处理。

我想通过handleMyCustomException方法处理MyCustomException,并通过handleGenericExceptions方法处理所有其他异常。 MyCustomException类扩展了Throwable。这有什么不对?

谢谢。

spring spring-boot exception
2个回答
0
投票

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

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


0
投票

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

Throwable类有两个重要的子类,Error和Exception。你的MyCustomException扩展Throwable。在Spring中,如果你的代码抛出了Throwable,那么Spring默认会把它装饰成IllegalStateException!我在spring4.3源代码中看到了这一点,如果你想证明这一点,你添加@ExceptionHandler({IllegalStateException})并使你的MyCustomException不被修改,这个方法会抓住它!

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

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

© www.soinside.com 2019 - 2024. All rights reserved.