Spring异常处理程序-处理多个异常

时间:2020-06-29 22:53:47

标签: spring spring-boot spring-mvc

下面是我的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'。我猜这是因为handle方法的方法参数是Exception A(我仍然希望错误消息应该显示No resolver for Exception B)。

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

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

使您自己的基类扩展RuntimeException

public class HandledRuntimeException extends RuntimeException{
}

并从您的异常类扩展该类,

public class ExceptionA extends HandledRuntimeException{
}

最后,在您的handle方法中,您可以进行如下更改

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