Adding a Global Exception Handler
We'll 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 of the exceptions. This exception handler method will generate user-friendly error messages with other related information.
You can make use of the Lombok library if approved by your respective 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; Â Â ...