Detail Springboot custom exception handling

  • 2020-06-19 10:17:44
  • OfStack

background

Springboot centralizes exception handling in one ModelAndView by default, but in the actual course of the project, this does not meet our requirements. For specific custom exception handling, see below

The specific implementation

If I have carefully read the exception handling details of spring boot and studied the source code, I think the specific implementation can not be read...

Override url for defining error pages. Default is 1 /error


@Bean
  public EmbeddedServletContainerCustomizer containerCustomizer(){
    return new EmbeddedServletContainerCustomizer(){
      @Override
      public void customize(ConfigurableEmbeddedServletContainer container) {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
        container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
        container.addErrorPages(new ErrorPage(java.lang.Throwable.class,"/error/500"));
      }
    };
  }

Rewrite ErrorController through the implementation of BasicErrorController, BasicErrorController rewrite the functional implementation


/**
 *  rewrite BasicErrorController, Mainly responsible for the system's exception page processing and error information display 
 * @see org.springframework.boot.autoconfigure.web.BasicErrorController
 * @see org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration
 *
 * @author Jonathan
 * @version 2016/5/31 11:22
 * @since JDK 7.0+
 */
@Controller
@RequestMapping(value = "error")
@EnableConfigurationProperties({ServerProperties.class})
public class ExceptionController implements ErrorController {

  private ErrorAttributes errorAttributes;

  @Autowired
  private ServerProperties serverProperties;


  /**
   *  Initialize the ExceptionController
   * @param errorAttributes
   */
  @Autowired
  public ExceptionController(ErrorAttributes errorAttributes) {
    Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
    this.errorAttributes = errorAttributes;
  }


  /**
   *  define 404 the ModelAndView
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(produces = "text/html",value = "404")
  public ModelAndView errorHtml404(HttpServletRequest request,
                 HttpServletResponse response) {
    response.setStatus(getStatus(request).value());
    Map<String, Object> model = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.TEXT_HTML));
    return new ModelAndView("error/404", model);
  }

  /**
   *  define 404 the JSON data 
   * @param request
   * @return
   */
  @RequestMapping(value = "404")
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error404(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.TEXT_HTML));
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);
  }

  /**
   *  define 500 the ModelAndView
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(produces = "text/html",value = "500")
  public ModelAndView errorHtml500(HttpServletRequest request,
                 HttpServletResponse response) {
    response.setStatus(getStatus(request).value());
    Map<String, Object> model = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.TEXT_HTML));
    return new ModelAndView("error/500", model);
  }


  /**
   *  define 500 The error JSON information 
   * @param request
   * @return
   */
  @RequestMapping(value = "500")
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error500(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.TEXT_HTML));
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);
  }


  /**
   * Determine if the stacktrace attribute should be included.
   * @param request the source request
   * @param produces the media type produced (or {@code MediaType.ALL})
   * @return if the stacktrace attribute should be included
   */
  protected boolean isIncludeStackTrace(HttpServletRequest request,
                     MediaType produces) {
    ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
    if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
      return true;
    }
    if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
      return getTraceParameter(request);
    }
    return false;
  }


  /**
   *  Get the wrong information 
   * @param request
   * @param includeStackTrace
   * @return
   */
  private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                          boolean includeStackTrace) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    return this.errorAttributes.getErrorAttributes(requestAttributes,
        includeStackTrace);
  }

  /**
   *  Does it include trace
   * @param request
   * @return
   */
  private boolean getTraceParameter(HttpServletRequest request) {
    String parameter = request.getParameter("trace");
    if (parameter == null) {
      return false;
    }
    return !"false".equals(parameter.toLowerCase());
  }

  /**
   *  Get error coding 
   * @param request
   * @return
   */
  private HttpStatus getStatus(HttpServletRequest request) {
    Integer statusCode = (Integer) request
        .getAttribute("javax.servlet.error.status_code");
    if (statusCode == null) {
      return HttpStatus.INTERNAL_SERVER_ERROR;
    }
    try {
      return HttpStatus.valueOf(statusCode);
    }
    catch (Exception ex) {
      return HttpStatus.INTERNAL_SERVER_ERROR;
    }
  }

  /**
   *  Implementation error path , Temporarily useless 
   * @see ExceptionMvcAutoConfiguration#containerCustomizer()
   * @return
   */
  @Override
  public String getErrorPath() {
    return "";
  }

}

conclusion

Step 1, by defining containerCustomizer, rewrites the view that corresponds to exception handling. 404 and 500 are currently defined and can be extended further.

Step 2: Override BasicErrorController to define a normal controller class that implements the view methods defined in Step 1. The purpose of the rewrite is to reuse ErrorAttributes. So the page, can get directly to the status, message, exception, trace, etc.

If you just treat the view handled by the exception as a static page and do not need to see the content of the exception information, just define error/404, error/500 and other static views after step 1.

ErrorController prints error responses in different formats based on the contents of the Accept header. For example, generate html pages for browser requests and json format returns for other requests


Related articles: