SpringBoot- error handling (XII)

SpringBoot default error handling mechanism

The browser returns a default error page

 

2. If another client, a default response json data

principle:

You can refer ErrorMvcAutoConfiguration; autoconfiguration error handling;

Added to the vessel the following components

1、DefaultErrorAttributes

帮我们在页面共享信息;
@Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
            boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
        errorAttributes.put("timestamp", new Date());
        addStatus(errorAttributes, requestAttributes);
        addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
        addPath(errorAttributes, requestAttributes);
        return errorAttributes;
    }

2, BasicErrorController: Default processing / error Request

@Controller 
@RequestMapping ( "$ {server.error.path: $ {error.path: / error}}" )
 public  class BasicErrorController the extends AbstractErrorController { 
    
    @RequestMapping (Produces = "text / html") // generated html data type ; browser sends a request to this method of treatment 
    public ModelAndView ErrorHtml (the HttpServletRequest request, 
            the HttpServletResponse Response) { 
        HttpStatus Status = the getStatus (request); 
        the Map <String, Object> = Model Collections.unmodifiableMap (getErrorAttributes ( 
                request, isIncludeStackTrace (request, MediaType.TEXT_HTML))); 
        response.setStatus (Status. value ()); 
        
        // to which page as the error page; the page containing the address and page content
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
    }

    @RequestMapping
    @ResponseBody    //产生json数据,其他客户端来到这个方法处理;
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

3、ErrorPageCustomizer

@Value ( "{$ error.path: / error}" )
     Private String path = "/ error"; After the system error to error process the request; (web.xml error page rules registered)

4、DefaultErrorViewResolver

@Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
            Map<String, Object> model) {
        ModelAndView modelAndView = resolve(String.valueOf(status), model);
        if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
            modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
        }
        return modelAndView;
    }

    private ModelAndView resolve(String viewName, Map<String, Object> model) {
        //The default SpringBoot can go to find a page? error / 404 
        String errorViewName = "error /" + viewName; 
        
        // template engine parses the page address is parsed template engine 
        TemplateAvailabilityProvider Provider = the this .templateAvailabilityProviders 
                .getProvider (errorViewName, the this .applicationContext);
         IF (! Provider = null ) {
             // return template engine case available to the address specified view errorViewName 
            return  new new ModelAndView (errorViewName, Model); 
        } 
        // template engine is not available, to find errorViewName static resource folder corresponding to the page error / 404.html 
        return resolveResource (errorViewName, Model); 
    }

step:

     However, a system error 4xx 5xx or the like occurs; ErrorPageCustomizer take effect (custom error response rule); will come / error request; will be BasicErrorController processed.

     Response page; to which the page is DefaultErrorViewResolver parsed;

protected ModelAndView resolveErrorView(HttpServletRequest request,
      HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
    //所有的ErrorViewResolver得到ModelAndView
   for (ErrorViewResolver resolver : this.errorViewResolvers) {
      ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
      if (modelAndView != null) {
         return modelAndView;
      }
   }
   return null;
}

How to customize error pages

1. there is the case of the template engine; error / status code ; [an error page named error status code in .html template engine folder inside the folder] error, this error status code corresponding to occur will come page;

We can use 4xx, and 5xx error page as a file name to match all errors of this type, precise priority (priority to find the exact status code .html);

Page information can be obtained;

timestamp: timestamp

status: Status Code

error: error

exception: exception object

message: Exception Message

errors: JSR303 data validation errors are here

2), no template engine (template engine can not find the error page), a static resource folder to find;

3), none of the above error page is the default came SpringBoot default error page;

How to customize error json data

1. & custom exception handler return custom data json

@ControllerAdvice
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }
}

2. forwarded to / error adaptive response effect processing

@ExceptionHandler (UserNotExistException. Class )
     public String handleException (Exception E, the HttpServletRequest Request) { 
        the Map <String, Object> = the Map new new HashMap <> ();
         // passed in our own error status code 4xx 5xx, or they will not enter a custom error page parsing process 
        / ** 
         * Integer statusCode = (Integer) Request 
         .getAttribute ( "javax.servlet.error.status_code"); 
         * / 
        request.setAttribute ( "javax.servlet.error.status_code", 500 ) ; 
        map.put ( "code", "user.notexist" ); 
        map.put ( "Message" , e.getMessage ());
        //To forward / error 
        return "Forward: / error" ; 
    }

We will carry out custom data

After an error occurs, to / error requests will be processed BasicErrorController, response data may be acquired by out getErrorAttributes obtained (predetermined method AbstractErrorController (ErrorController));

1, a full write ErrorController of [implementation class or subclass AbstractErrorController prepared in], placed in a container;

2, the page data can be, or can return json data are obtained by errorAttributes.getErrorAttributes;

Vessel DefaultErrorAttributes.getErrorAttributes (); default data processing;

Custom ErrorAttributes

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
        map.put("company","atguigu");
        return map;
    }
}

 

Guess you like

Origin www.cnblogs.com/xiaoqiqistudy/p/11366415.html