When we are doing web applications, it is very common for errors to occur during request processing. At this time, unified exception handling is needed. This article mainly introduces to you the relevant information on how Spring Boot implements unified exception handling. Friends in need can refer to it. Let’s take a look together.
Spring Boot has error mapping by default, but this error page is not very user-friendly.
Unified exception handling
Define a class for unified exception handling by using @ControllerAdvice instead of defining it one by one in each Controller.
@ExceptionHandler is used to define the function type that the function targets, and finally maps the Exception object and request URL to the URL.
@ControllerAdvice class ExceptionTranslator { public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } }
Implement error.html page display
Create error.html in the templates directory.
For example:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>统一异常处理</title> </head> <body> <h1>Error Handler</h1> <p th:text="${url}"></p> <p th:text="${exception.message}"></p> </body> </html>
Return using Json format
Just add in @ Adding @ResponseBody after ExceptionHandler can convert the content of the processing function return into JSON format
Create a JSON return object, such as:
public class ErrorDTO implements Serializable { private static final long serialVersionUID = 1L; private final String message; private final String description; private List<FieldErrorDTO> fieldErrors; //getter和setter省略 }
Exception handling can be added for the specified Exception
@ExceptionHandler(ConcurrencyFailureException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorDTO processConcurencyError(ConcurrencyFailureException ex) { return new ErrorDTO(ErrorConstants.ERR_CONCURRENCY_FAILURE); }
ErrorConstants.ERR_CONCURRENCY_FAILURE is an exception message defined.
Summarize
The above is the detailed content of Detailed explanation of Spring Boot unified exception handling example code. For more information, please follow other related articles on the PHP Chinese website!