It is a common requirement for all Web projects to deal with all kinds of exceptions in the process of business execution. Spring, as the most popular Web framework, naturally provides a solution.
Spring’s unified exception handling
In Spring 3.2, the @ControllerAdvice and @RestControllerAdvice annotations were added to enhance our Controller layer.
In a class annotated with @ControllerAdvice or @RestControllerAdvice annotations, the following annotations can be used to implement different functions
- @ExceptionHandler: Global exception processing
- InitBinder: Global data binding
- @modelAttribute: global data preprocessing
For global exception handling, this is done by creating the @ControllerAdvice class and customizing the @ExceptionHandler method.
The instance
Here is a common design for your reference.
It is mainly divided into the following parts
- Custom global status code
- Custom exception classes
- Custom business result classes
- Custom unified exception handling classes
- Use custom exceptions
Custom global status code
Each business state has a status code
Custom exception classes
Each exception applies to an ApplicationEnum
Custom business result classes
Custom business result classes to unify all controller layer return values
Create a SuccessResult and a FailResult for ease of use
Custom exception handling classes
If an Exception can match more than one @ExceptionHandler, select the Exception with the least depth of matching (that is, the Exception that best matches).
Refer to the article