【问题标题】:Spring Exception handler - Handling multiple exceptionsSpring 异常处理程序 - 处理多个异常
【发布时间】:2020-06-29 22:53:47
【问题描述】:

下面是我的 ExceptionHandler 方法,用于处理可以从服务类抛出的不同异常。

@ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handle(ExceptionA e) {
    log.error("Exception occurred: {} {}", e.getMessage(), e);
}

当抛出 ExceptionA 时,一切都按预期工作。但是当抛出 ExceptionB 时,它会给出错误No suitable resolver for argument 0 of type 'ExceptionA'。我猜是因为句柄方法的方法参数是异常A(我仍然希望错误消息应该是No resolver for Exception B)。

handle 方法的方法参数应该是什么,以便它可以处理 3 个异常中的任何一个?

注意:所有异常都是通过从 RuntimeException 扩展来创建的。

【问题讨论】:

    标签: spring spring-boot spring-mvc


    【解决方案1】:

    你需要一个通用的基类作为参数类型,例如 RuntimeException:

    @ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public void handle(RuntimeException e) {
        log.error(e.getMessage(), e);
    }
    

    【讨论】:

    • 现在这个方法处理每个扩展 RuntimeException 的异常。我希望这个方法只处理这 3 个异常之一
    • @KumarV 不,它没有。该方法只处理@ExceptionHandler中定义的异常。
    【解决方案2】:

    制作你自己的扩展 RuntimeException 的基类

    public class HandledRuntimeException extends RuntimeException{
    }
    

    并从您的异常类中扩展此类,例如,

    public class ExceptionA extends HandledRuntimeException{
    }
    

    最后,在你的处理方法中,你可以改变如下

    @ExceptionHandler({HandledRuntimeException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public void handle(HandledRuntimeException e) {
        log.error("Exception occurred: {} {}", e.getMessage(), e);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 2019-12-28
      • 2012-03-04
      • 1970-01-01
      • 2013-09-22
      • 2011-02-03
      相关资源
      最近更新 更多