I have a exception class like follows
@ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Unprocessable Entity") // 422
public class UnprocessableEntityException extends RuntimeException {
}
Now the status is not returned as 422 unless I write a specific handler in the Controller class like :
@ExceptionHandler(UnprocessableEntityException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public String handleException(Exception ex) {
...
}
As I understand I should not need @ExceptionHandler in first place, not sure what am I missing.
Spring provides a few primary ways to return custom status codes from its Controller classes: using a ResponseEntity. using the @ResponseStatus annotation on exception classes, and. using the @ControllerAdvice and @ExceptionHandler annotations.
If we want to specify the response status of a controller method, we need to annotate that method with the @ResponseStatus annotation. It has two interchangeable arguments for the desired response type: code and value. Note, that when we set reason, Spring calls HttpServletResponse. sendError().
The @ResponseStatus annotation can be used on any method that returns back a response to the client.
We can use @ResponseStatus to mark a method or an exception class with a status code and reason that should be returned. On invoking the marked handler method or when a specified exception is thrown, the HTTP status will be set to the one defined using @ResponseStatus annotation.
Throwing a @ResponseStatus
annotated exception from a controller method should be enough for the framework to write the HTTP status code - no @ExceptionHandler
necessary.
The following will write a 422 Status on hitting the webapp root as expected:
@Controller
public class ExceptionController {
@RequestMapping("/")
public void action() {
throw new ActionException();
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "nope")
public static class ActionException extends RuntimeException {}
}
This works courtesy of the ResponseStatusExceptionResolver
which is created by Spring MVC by default - if it's not working for you, my guess is that this default exception resolver has been removed (by e.g. overriding WebMvcConfigurationSupport.configureHandlerExceptionResolvers
or otherwise configuring your context's HandlerExceptionResolver
s so that the ResponseStatusExceptionResolver
is trumped.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With