首页 > 解决方案 > 是否可以在 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方法而不在参数中提供请求对象,但我确实需要该对象来填充我的日志中的某些字段以用于监控目的。

标签: javaspringexceptionhandlercontroller-advice

解决方案


推荐阅读