Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @ControllerAdvice annotation in spring-boot and why we use it and when?

I'm using custom framework in my work built on spring-boot framework , and i see this annotation @ControllerAdvice in spring-boot when i need it to create custom exception handler class but i don't know why i must use it ?

like image 433
Abd Abughazaleh Avatar asked Aug 30 '19 18:08

Abd Abughazaleh


1 Answers

@ControllerAdvice is very useful to handle exceptions when you have multiple Spring REST API controllers doing a lot of different work.

That means when writing any application you encounter exceptions and to handle them at each method level is tedious and not optimal. So in order to overcome that, spring has introduced the concept of @ControllerAdvice which will intercept all the controllers and look for the exceptions thrown. This is at a global level means you only have one @ControllerAdvice for each application and it will intercept the exceptions thrown by the controllers in that particular application context. For more information

Note: It should be used only with spring MVC controllers.

like image 163
Brooklyn99 Avatar answered Nov 07 '22 05:11

Brooklyn99