Alfredo Morales
Alfredo Morales

Reputation: 93

error trying to catch @valid with ExceptionHandler

I have a Spring web app with a REST controller like this:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
public @ResponseBody ResponseEntity<Resp> do(@Valid @RequestBody(required = true) Body b){

my object has validations like these:

public class Body implements Serializable {
    @NotEmpty
    @Max(value = 32)
    private String nss;

and my @ExceptionHandler is this:

@ControllerAdvice
public class Handler extends ResponseEntityExceptionHandler {

      @ExceptionHandler(value = { MethodArgumentNotValidException.class })
      public ResponseEntity<RespError> invalidInput(RuntimeException ex) {
          RespErrorresponse = new RespError();
          return new ResponseEntity<RespError>(response, HttpStatus.BAD_REQUEST);
      }

I'm trying to catch the not valid exception but everytime I'm trying to start the app, I'm getting:

java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public org.springframework.http.ResponseEntity com.algoApp.controller.RestResponseEntityExceptionHandler.invalidInput(java.lang.RuntimeException), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}

how should I implement the handler to catch this exception instead?

Upvotes: 1

Views: 1044

Answers (1)

Gaurav
Gaurav

Reputation: 3749

In my experience, matching arguments works.

@ControllerAdvice
public class Handler extends ResponseEntityExceptionHandler {

      @ExceptionHandler(value = { MethodArgumentNotValidException.class })
      public ResponseEntity<RespError> invalidInput(MethodArgumentNotValidExceptionex) {
          RespErrorresponse = new RespError();
          return new ResponseEntity<RespError>(response, HttpStatus.BAD_REQUEST);
      }
}

Upvotes: 1

Related Questions