1

I have a task to handle all exceptions in my project via @ControllerAdvice. The project has multiple controller methods. I have a custom exception which is thrown by some of these controller methods.
For handling this exception, I have a class annotated with @ControllerAdvice and I have written some @ExceptionHandler methods.

@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();
  }
}

Doing this throws an IllegalStateException
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class com.action.resource.WebServiceContactException]

Is there anyway I can define multiple @ExceptionHandler methods dealing with same exception WebServiceContactException but with different web requests?
PS : I know I can write @ExceptionHandler method without giving request object in argument but I really need that object to populate certain fields in my logs for monitoring purposes.

Bhupesh_decoder
  • 75
  • 1
  • 11
  • Can you use multiple `@ControllerAdvice` ? We use different `@ControllerAdvice` for different controller files. – Shawrup Aug 24 '21 at 18:43

0 Answers0