Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of @ControllerAdvice over @ExceptionHandler or HandlerExceptionResolver for handling exceptions?

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?

like image 968
Rajorshi Roy Avatar asked Feb 10 '16 18:02

Rajorshi Roy


1 Answers

@ExceptionHandler

@ExceptionHandler works at the Controller level and it is only active for that particular Controller, not globally for the entire application.

HandlerExceptionResolver

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

@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.

like image 179
Bacteria Avatar answered Sep 23 '22 13:09

Bacteria