Spring boot integrated global exception handling
Preface
For normal MVC projects, a large number of exceptions need to be handled by us. In this way, our Controller layer has to make exceptions in the try catch service layer. In this way, each method body of the Controller layer needs to write some templated try catch code, which is very difficult to see and redundant, and is not easy to maintain.
HOW TO DO
Two annotation classes are involved here: *The global exception handling class of controlleradvise no longer needs to be defined one by one in each Controller *The @ ExceptionHandler defines exceptions for each type Of course, if you've tried to catch in your business, don't expect to be dealt with. You've dealt with it yourself Of course, other people don't worry
Global processing class:
@ControllerAdvice @ResponseBody public class GlobalExceptionHandler { @Autowired private AppResultManager res;//Return result wrapper class /** * Handler for parameter validation failure, such as handling of validation failure using org.springframework.util.Assert class * * @param request HttpServletRequest * @param exception catch ConstraintViolationException */ @ExceptionHandler(value = IllegalArgumentException.class) public String assertFailHandler(HttpServletRequest request, IllegalArgumentException exception) { return res.error(exception.getMessage()); } //... omit other methods /** * All exceptions error Handler, bottom cover * * @param request HttpServletRequest * @param exception Exception * @throws Exception error */ @ExceptionHandler(value = Exception.class) public String allExceptionHandler(HttpServletRequest request, Exception exception) { exception.printStackTrace(); return res.error(exception.toString()); } }
Test code:
@RestController @RequestMapping(value = "/helloWorld") public class HelloWorldController { @Autowired private AppResultManager res; @RequestMapping(value = "/test",method = RequestMethod.GET) public String testException(String userName, String callback) { Assert.notNull(userName, "userName can't found"); return res.success(userName, callback); } }
Browser access:
http://localhost:8080/helloWorld/test
Advantages and disadvantages
Advantages: handle exceptions of Controller layer and data verification in a unified way, reduce template code, reduce coding amount, and improve scalability and maintainability. Disadvantages: only exceptions that are not caught (thrown out) by the Controller layer can be handled. For exceptions in the Interceptor layer and exceptions in the Spring framework layer, nothing can be done.