Global Exception Handling Using ControllerAdvice And ExceptionHandler Annotation
Posted By : Shakil Pathan | 31-May-2018
In this blog, I am going to explain you about how to handle global exception from your controllers in your spring web application. Spring provides @ControllerAdvice annotation which allows you to write some global code which can be applied to the controllers in your web application. This annotation will apply, by default, to all the classes with the @Controller annotation (which extends to @RestController). You can configure it to use multiple packages those can also be chosen by following the below process:
@ControllerAdvice("my.package")
@ControllerAdvice(value = "my.package")
@ControllerAdvice(basePackages = "my.package")
@ControllerAdvice annotation's basePackageClasses property provides another way to specify a package, which will enable this to all the controllers inside the package that the class lives in:
@ControllerAdvice(basePackageClasses = MyClass.class)
you can also apply it to controllers with certain annotations:
@ControllerAdvice(annotations = Controller.class)
@ExceptionHandler, as the name suggests, allow you to define a method that handles exceptions. If you are not using the @ControllerAdvice annotation, then the code for handling those exceptions would be in the controller itself, which obviously add some duplication and clutter to the class. By using @ControllerAdvice along with @ExceptionHandler allows you to prevent this by providing globle error handling and more specifically.
@ControllerAdvice
public class GlobalExceptionHandler {
public ResponseEntity<object> handleInternal(final CustomException ex, final WebRequest request) {
String body = "Entity not found.";
return new ResponseEntity<object>(body, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
Using @ControllerAdvice and @ExceptionHandler, a custom response is returned (so the stacktrace not found anymore).
Hope, It helps you to understanding the concept.
Thanks,
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .