6

I'm trying to override the handleMethodArgumentNotValid method. But I'm still getting the error:

Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]

I've overridden the method as suggested in various posts (for example in Spring Rest ErrorHandling @ControllerAdvice / @Valid) like this:

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
        String message = errorMessageBuilder(ex);
        return handleExceptionInternal(ex, message, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, webRequest);
    }
}

What am I doing wrong?

Sincerely,

Marcel

  • The error message mentions ambiguity. That sounds like there are multiple exception handlers for the same exception class and the compiler won't pick a random one. I have no idea about a solution though. – f1sh Jan 28 '20 at 15:35
  • I know what the message means, Spring handles it internally as well, that's why I'm overriding it (Extending the class at first, then override it.) – Marcel Oostebring Jan 28 '20 at 15:40
  • @MarcelOostebring please check my answer, this will help you https://stackoverflow.com/a/57961101/10426557 if this helps upvote please... – Jonathan JOhx Jan 28 '20 at 16:30
  • @One guy that unfortunately did not help me. I'm still getting the ambigious exception handler method mapped error. – Marcel Oostebring Jan 29 '20 at 07:02
  • May help someone, I got it working with this : https://stackoverflow.com/a/68888906/3412696 – Rafi Aug 23 '21 at 08:16
  • I think the Spring boot version is causing the problem. Unfortunately, in some of tutorials the versions are not mentioned and the speed of change is insane these days. – Ehsan Shekari Jan 05 '23 at 11:43

1 Answers1

7

If you want to create your own response, then try with the below code.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
        Map<String, Object> body = new HashMap<>();
        body.put("error", ex);
        return new ResponseEntity<>(body, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}

You can change the Map to your customize object and set the error pieces of information you want. I hope it will work.

Yogeen Loriya
  • 589
  • 2
  • 5
  • 3
    Yes, I've found a working way by now. Either not extending the ResponseEntityExceptionHandler, or if you do extend that class, remove @ExceptionHandler(MethodArgumentNotValidException.class) worked too. – Marcel Oostebring Jan 29 '20 at 09:16