Adding a Global Exception Handler
We have multiple controllers that consist of multiple methods. Each method may have checked exceptions or throw runtime exceptions. We should have a centralized place to handle all these errors for better maintainability and modularity and clean code.
Spring provides an AOP feature for this. We just need to write a single class annotated with @ControllerAdvice
. Then, we just need to add @ExceptionHandler
for each type of exception. This exception handler method will generate user-friendly error messages with other related information.
You can make use of the Project Lombok library if approved by your organization for third-party library usage. This will remove the verbosity of the code for getters, setters, constructors, and so on.
Let’s first write the Error
class in the exceptions
package that contains all the error information:
public class Error { private static final long serialVersionUID = 1L; private...