Unified exception handling details

  • 2020-06-03 06:31:15
  • OfStack

Spring Boot has error mapping by default, but this error page is not user-friendly.

Unified exception handling

By using @ControllerAdvice to define classes that unify 1 exception handling, instead of defining them individually in each Controller.

The @ExceptionHandler is used to define the function type for which the function is targeted, and finally the Exception object and request URL are mapped to 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;
 }
}

error. html page display

Create error.html in the templates directory.

Such as:


<!DOCTYPE html> 
<html> 
<head lang="en"> 
 <meta charset="UTF-8" />
 <title> system 1 Exception handling </title>
</head> 
<body> 
 <h1>Error Handler</h1>
 <div th:text="${url}"></div>
 <div th:text="${exception.message}"></div>
</body> 
</html>

Return to Json format

Simply add @ResponseBody after @ExceptionHandler to convert the contents of the handler return to JSON format

Create 1 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 and setter omit 
}

You can add exception handling 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 defined as 1 exception information.

conclusion

The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: