Spring 3.2 introduced @ControllerAdvice
annotation for handling exceptions in a Spring MVC application. But prior to this version Spring had @ExceptionHandler
or HandlerExceptionResolver
to handling exceptions in a Spring MVC application. Then why Spring 3.2 introduced @ControllerAdvice
annotation for handling exceptions? I strongly believe that Spring 3.2 introduced @ControllerAdvice
annotation to address the limitations of @ExceptionHandler
or HandlerExceptionResolver
or make the exceptions handling more stronger.
Can any one explain the advantages of @ControllerAdvice
over @ExceptionHandler
or HandlerExceptionResolver
for handling exceptions?
@ExceptionHandler
works at the Controller level and it is only active for that particular Controller, not globally for the entire application.
This will resolve any exception thrown by the application. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes. It does not have control over the body of the response, means it does not set anything to the body of the Response.It does map the status code on the response but the body is null.
@ControllerAdvice
used for global error handling in the Spring MVC application.It also has full control over the body of the response and the status code.
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