简体   繁体   中英

Why @ExceptionHandler(MethodArgumentNotValidException.class) is ignored in favour of @ExceptionHandler(Exception.class)

I know that Exception is the Parent of all exceptions but I thought when you set @ExceptionHandler with specific exception class this should handle that specific exception.

Maybe you can point what I have missed in following code so MethodArgumentNotValidException will go into processValidationError method not processError method.

@ControllerAdvice
public class ExceptionHandler {

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ValidationErrorDTO processError(Exception e) {
    return processErrors(e);
  }
 }

  @ControllerAdvice
public class OtherExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    return processErrors(ex);
}
}

After your edit it's clear that you have more than one @ControllerAdvice class.

In short, the problem is that your ExceptionHandler class (and its @ExceptionHandler for Exception.class ) gets registered first by Spring, and because Exception handler matches any exception, it will be matched before Spring ever gets to more specific handlers defined.

You can read detailed explanation in @Sotirios answer here .

I'd recommend you register only one ControllerAdvice and to make sure it extends ResponseEntityExceptionHandler , so the default handling of MethodArgumentNotValidException is not overwritten.

If you then wish to alter the logic of handling the MethodArumentNotValidException , you can override the handleMethodArgumentNotValid method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM