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

Abd Abughazaleh :

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 ?

Santossh Kumhar :

@ControllerAdvice is very useful to handle exceptions when you have multiple 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. For more information here is a nice explanation:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309075&siteId=1