@ControllerAdvice and Exception handling

The exception handing is a powerful feature of Java. Exception handling allows us to handle any exception which occurs at runtime and stop to break the normal flow of a program.

@ControllerAdvice is a class level annotation which helps us to handle exceptions globally across all of the controllers and web framework

@ContollerAdvice is one of the centralized cross-cutting concerns, which means it comes into play if any controller code throws an exception.

Cross-cutting concerns are parts of a program that rely on or must affect many other parts of the system. This is like injecting complete module(logging, cahcing, etc ) in Spring framework dynamically.

Exception, Logging, caching, security, monitoring, etc. are some of the examples cross cutting concern from AOP. At any point of time there modules can be added/included dynamically.

@ExceptionHandler which is method level annotation allow us to handle exception at run time as shown below.

In the following screen, the first method will specifically catch PracticeException which is custom is nature, while the second method will handle all other exceptions.

Create custom PracticeException class having error code, message and timestamp. 

Throw exception accordingly as shown below:

Making a Postman call will throw the following PracticeException if no record is found with the specified ID:

Note: We can apply exception handler class to specific controller package using base packages as shown below:

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 12 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0