java - 是否可以在 ControllerAdvice 中有多个 ExceptionHandler 用于相同的异常但不同的 Web 请求?
问题描述
我的任务是通过@ControllerAdvice
. 该项目有多个控制器方法。我有一个自定义异常,它是由其中一些控制器方法引发的。
为了处理这个异常,我有一个用注释的类,@ControllerAdvice
并且我写了一些@ExceptionHandler
方法。
@EnableWebMvc
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(WebServiceContactException.class)
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
@ResponseBody
public MyResponse dealWebServiceContactExceptionForAddElement(WebServiceContactException e, AddRequest request) {
int errorCode = HttpStatus.PRECONDITION_FAILED.value();
LOGGER.error("Failed to contact service for " + request.getFunctionalId(), e);
auditTrail.reportFailureInfo(e.getMessage());
return MyResponse.Builder.newBuilder(errorCode)
.setDescription(Constants.EXECUTION_FAILED)
.build();
}
@ExceptionHandler(WebServiceContactException.class)
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
@ResponseBody
public MyResponse dealWebServiceContactExceptionForDeleteElement(WebServiceContactException e, DeleteRequest request) {
int errorCode = HttpStatus.PRECONDITION_FAILED.value();
LOGGER.error("Failed to contact service for " + request.getFunctionalId(), e);
auditTrail.reportFailureInfo(e.getMessage());
return MyResponse.Builder.newBuilder(errorCode)
.setDescription(Constants.EXECUTION_FAILED)
.build();
}
}
这样做会引发IllegalStateException
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class com.action.resource.WebServiceContactException]
无论如何我可以定义多个@ExceptionHandler
处理相同异常WebServiceContactException
但处理不同网络请求的方法吗?
PS:我知道我可以编写@ExceptionHandler
方法而不在参数中提供请求对象,但我确实需要该对象来填充我的日志中的某些字段以用于监控目的。
解决方案
推荐阅读
- javascript - 如何让 Angular 在编译时检测 @NgModule 中不匹配的提供程序?
- swift - MKPointAnnotation 如何隐藏标记图像
- jquery - 响应按钮单击时未显示模态弹出窗口
- python - 在 python 中加载 npz 文件的内容时出现 NameError
- flutter - Flutter Bloc Equatable 状态,在所有状态类中具有一个共同属性
- text-to-speech - 为什么 TTS(文本转语音)提示在一种环境中测试时可以正常播放,而在其他环境中则不能?
- model - Laravel:找不到Modo类
- laravel - 如何使用 Authentication 的 /user api 来使用 Laravel 资源
- c++ - 初始化等式 C++ 的顺序
- matlab - 在 Matlab 中绘制两个具有相同焦点的椭圆