从@ExceptionHandler 抛出异常以被另一个处理程序捕获

age*_*nzo 7 java spring-mvc exceptionhandler

我有一个@ControllerAdvice类来处理来自 SpringMVC 控制器的异常。我想在方法中捕获已知类型 (RuntimeException)@ExceptionHandlere.getCause()异常,然后抛出异常并让同一个 @ControllerAdvice 类捕获此异常。

示例代码:

@ControllerAdvice
public class ExceptionHandlingAdvice
{
    @ExceptionHandler( RuntimeException.class )
    private void handleRuntimeException( final RuntimeException e, final HttpServletResponse response ) throws Throwable
    {
        throw e.getCause(); // Can be of many types
    }

    // I want any Exception1 exception thrown by the above handler to be caught in this handler
    @ExceptionHandler( Exception1.class )
    private void handleAnException( final Exception1 e, final HttpServletResponse response ) throws Throwable
    {
        // handle exception
    }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

May*_*day 1

您可以检查 RuntimeException 是否是 Exception1.class 的实例并直接调用该方法:

 private void handleRuntimeException( final RuntimeException e, final HttpServletResponse response ) throws Throwable
{
    if (e instanceof Exception1) handleAnException(e,response);
    else throw e.getCause(); // Can be of many types
}
Run Code Online (Sandbox Code Playgroud)