gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:07:06 25 4
gpt4 key购买 nike

我有一个 @ControllerAdvice类来处理来自我的 SpringMVC Controller 的异常。我想在 @ExceptionHandler 中捕获已知类型的异常 (RuntimeException)方法然后抛出 e.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
}
}

这可能吗?

最佳答案

您可以检查该 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
}

关于java - 从@ExceptionHandler 抛出异常以被另一个处理程序捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com