Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
}
like image 984
user1048282 Avatar asked Oct 24 '13 13:10

user1048282


People also ask

Can we have two controller advice in spring boot?

Spring can process controller advice classes in any order unless we have annotated it with the @Order annotation. So, be mindful when you write a catch-all handler if you have more than one controller advice. Especially when you have not specified basePackages or annotations in the annotation.

How does spring boot handle runtime exception?

Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API.

Can we handle exceptions in spring boot?

Exception Handling in Spring Boot helps to deal with errors and exceptions present in APIs so as to deliver a robust enterprise application. This article covers various ways in which exceptions can be handled in a Spring Boot Project.

How do you throw an exception using ResponseEntity?

You have to provide implementation to use your error handler, map the response to response entity and throw the exception. Create new error exception class with ResponseEntity field. Custom error handler which maps the error response back to ResponseEntity.


1 Answers

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.

like image 184
Michał Rybak Avatar answered Sep 21 '22 13:09

Michał Rybak