Springboot的错误处理机制

    相信以下这个页面对大家来说并不陌生,当我们启动一个Springboot应用的时候,如果在浏览器访问错误,Springboot就会自动响应这个界面,如果不是在浏览器访问,比如在postman去访问,springboot响应回来的则是json数据,今天就来探究下springboot对错误的处理机制。

浏览器响应:
在这里插入图片描述
Postman响应:
在这里插入图片描述
首先Springboot在启动的时候,会帮我们加载很多配置类,这其中也包括错误自动配置类,处理的大概流程如下:

  1. 一但系统出现4百多或者5百多之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则)
  2. 就会来到/error,请求;就会被BasicErrorController处理。如果是浏览器请求BasicErrorController会调用ErrorViewResolver的resolveErrorView方法来解析视图
  3. 响应页面,ErrorMvcAutoConfiguration中配置了一个默认的错误视图解析器DefaultErrorViewResolver 去哪个页面是由DefaultErrorViewResolver解析得到的;

接下来根据这个流程来看看错误配置类的处理。

代码如下:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})//只有存在这两个类,这个错误自动配置类才会生效
@AutoConfigureBefore({WebMvcAutoConfiguration.class})
@EnableConfigurationProperties({ServerProperties.class, WebMvcProperties.class})//先使ServerProperties和WebMvcProperties的配置生效
public class ErrorMvcAutoConfiguration {
    private final ServerProperties serverProperties;

    public ErrorMvcAutoConfiguration(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }
 // ....省略部分代码
    @Bean
    @ConditionalOnMissingBean(
        value = {ErrorController.class},
        search = SearchStrategy.CURRENT
    )
    //这个方法上的BasicErrorController是核心,我们点进去看看,代码贴在下方
    public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        return new BasicErrorController(errorAttributes, this.serverProperties.getError(), (List)errorViewResolvers.orderedStream().collect(Collectors.toList()));
    }

    @Bean
    public ErrorMvcAutoConfiguration.ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
        return new ErrorMvcAutoConfiguration.ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
    }

============
//下面代码位于ErrorMvcAutoConfiguration.class之中
//一但系统出现4百多或者5百多之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则)
//定制一些错误页面信息,并发出/error请求
	@Bean
    public ErrorMvcAutoConfiguration.ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
        return new ErrorMvcAutoConfiguration.ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
 }


============
//下面代码位于BasicErrorController.class之中
//BasicErrorController:处理默认/error请求 
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})//可以看到这个类是用来拦截/error请求的
public class BasicErrorController extends AbstractErrorController {   
  .......省略部分代码

    @RequestMapping(
        produces = {"text/html"}//对于html类型的数据,浏览器的请求会被转发到这个方法来处理
    )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());//设置响应的状态码
        //下面两步是决定去哪个错误页面,并且携带哪些数据,其中重点在resolveErrorView这个方法,也是对应着流程的第三步,代码贴在下面
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null ? modelAndView : new ModelAndView("error", model);
    }

    @RequestMapping//对于非浏览器的请求,比如Postman则来到这个方法进行处理
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        //返回的是json数据
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity(status);
        } else {
            Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
            return new ResponseEntity(body, status);
        }
    }

============
//下面代码位于AbstractErrorController.class之中,也就是BasicErrorController的父类
//响应页面;去哪个页面是由DefaultErrorViewResolver解析得到的;

protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
    Iterator var5 = this.errorViewResolvers.iterator();
    ModelAndView modelAndView;
    do {
        if (!var5.hasNext()) {
            return null;
        }
        //通过错误视图解析器的resolveErrorView,得到ModelAndView,至于错误视图解析器, ErrorMvcAutoConfiguration也配置了一个就是DefaultErrorViewResolver
        ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
        modelAndView = resolver.resolveErrorView(request, status, model);
    } while(modelAndView == null);

    return modelAndView;
}

//下面代码位于ErrorMvcAutoConfiguration.class之中
//DefaultErrorViewResolver被加入到容器之中
@Bean
@ConditionalOnBean({DispatcherServlet.class})
@ConditionalOnMissingBean({ErrorViewResolver.class})
DefaultErrorViewResolver conventionErrorViewResolver(z) {
    return new DefaultErrorViewResolver(this.applicationContext, this.resources);
}

//DefaultErrorViewResolver
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {

static {
    Map<Series, String> views = new EnumMap(Series.class);
    views.put(Series.CLIENT_ERROR, "4xx");
    views.put(Series.SERVER_ERROR, "5xx");
    SERIES_VIEWS = Collections.unmodifiableMap(views);
}
//重点方法
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, 		Map<String, Object> model) {
    ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
        modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
        //调用了resolve方法,传入的第一个参数为响应的状态码
    }

    return modelAndView;
}

private ModelAndView resolve(String viewName, Map<String, Object> model) {
 //viewName为响应状态码,所以默认找到的响应页面就是error/状态码
    String errorViewName = "error/" + viewName;
   //调用模板引擎去解析,
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
    //如果模板引擎可用,就返回到errorViewName指定的视图地址
    return provider != null ? new ModelAndView(errorViewName, model) :
     		this.resolveResource(errorViewName, model);//模板引擎不可用就调用resolveResource方法

}
//resolveResource
//在静态资源文件夹下找到viewName页面
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
    String[] var3 = this.resources.getStaticLocations();
    int var4 = var3.length;
    for(int var5 = 0; var5 < var4; ++var5) {
        String location = var3[var5];
        try {
            Resource resource = this.applicationContext.getResource(location);
            resource = resource.createRelative(viewName + ".html");
            if (resource.exists()) {
                return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
            }
        } catch (Exception var8) {
        }
    }
    return null;
}

============
//上面就是默认返回的响应页面的流程,至于这返回响应页面中的数据信息从何而来呢,我们回到BasicErrorController中
@RequestMapping(
    produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = this.getStatus(request);
    //model就是存放返回页面的数据,通过getErrorAttributes来获得数据
    Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
    return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
//getErrorAttributes中有又调用了errorAttributes.getErrorAttributes
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
    WebRequest webRequest = new ServletWebRequest(request);
    return this.errorAttributes.getErrorAttributes(webRequest, options);
}
//errorAttributes的定义为 private final ErrorAttributes errorAttributes;它的具体实现类是DefaultErrorAttributes,点进去这个方法可以看到getErrorAttributes
@Deprecated
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new LinkedHashMap();
    errorAttributes.put("timestamp", new Date());//时间戳
    this.addStatus(errorAttributes, webRequest);//状态码
    this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);//错误信息
    this.addPath(errorAttributes, webRequest);
    return errorAttributes;
}

上面就是Springboot一个大概的错误异常处理机制了,根据上面的代码,我们也可以得出一些信息,用于来定制我们自己的错误响应页面

  • 定制错误页面,(1)有模板引擎的情况下,将自己的错误页面放在以下路径,就可以默认响应这个页面
    在这里插入图片描述
    当然这里的页面也可以写成4XX.html 和 5XX.html,进行模糊匹配

(2)没有模板引擎的话,就会在静态资源文件夹里面去找对应的页面
(3)静态资源文件夹下也没有,就会返回Springboot默认的错误页面,默认错误页面名字为error,如下代码:

//ErrorMvcAutoConfiguration.class中,有这样一个defaultErrorView。默认的beanName就为error
@Bean(
    name = {"error"}
)
@ConditionalOnMissingBean(
    name = {"error"}
)
public View defaultErrorView() {
    return this.defaultErrorView;
}
//defaultErrorView定义如下
private final ErrorMvcAutoConfiguration.StaticView defaultErrorView = new ErrorMvcAutoConfiguration.StaticView();

//可以看到它的类型实际为StaticView,而StaticView就是渲染出默认错误页面
private static class StaticView implements View {
    private static final MediaType TEXT_HTML_UTF8;
    private static final Log logger;

    private StaticView() {
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (response.isCommitted()) {
            String message = this.getMessage(model);
            logger.error(message);
        } else {
            response.setContentType(TEXT_HTML_UTF8.toString());
            StringBuilder builder = new StringBuilder();
            Object timestamp = model.get("timestamp");
            Object message = model.get("message");
            Object trace = model.get("trace");
            if (response.getContentType() == null) {
                response.setContentType(this.getContentType());
            }
            builder.append("<html><body><h1>Whitelabel Error Page</h1>").append("<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>").append("<div id='created'>").append(timestamp).append("</div>").append("<div>There was an unexpected error (type=").append(this.htmlEscape(model.get("error"))).append(", status=").append(this.htmlEscape(model.get("status"))).append(").</div>");
            if (message != null) {
                builder.append("<div>").append(this.htmlEscape(message)).append("</div>");
            }
            if (trace != null) {
                builder.append("<div style='white-space:pre-wrap;'>").append(this.htmlEscape(trace)).append("</div>");
            }
            builder.append("</body></html>");
            response.getWriter().append(builder.toString());
        }
    }
    private String htmlEscape(Object input) {
        return input != null ? HtmlUtils.htmlEscape(input.toString()) : null;
    }
    private String getMessage(Map<String, ?> model) {
        Object path = model.get("path");
        String message = "Cannot render error page for request [" + path + "]";
        if (model.get("message") != null) {
            message = message + " and exception [" + model.get("message") + "]";
        }
        message = message + " as the response has already been committed.";
        message = message + " As a result, the response may have the wrong status code.";
        return message;
    }
    public String getContentType() {
        return "text/html";
    }
    static {
        TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);
        logger = LogFactory.getLog(ErrorMvcAutoConfiguration.StaticView.class);
    }
}

当然处理定制错误异常响应页面,我们也可以定制错误异常响应json数据

//第一种方式,自定义异常处理器
@ControllerAdvice
public class MyExceptionHandler {
	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Map<String,Object> handleException(Exception e){
		Map<String,Object> map = new HashMap<>();
		map.put("message",e.getMessage());
		return map;
	}
} 
//这种方式有问题,在浏览器访问也会变成json数据
//第二种方式
@ExceptionHandler(Exception.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
* Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
*/
	request.setAttribute("javax.servlet.error.status_code",404);
	map.put("message",e.getMessage());
	//转发到/error
	return "forward:/error";
}
//这种方式不能将我们自定义的数据携带出去
//第三种方式
/*出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由
getErrorAttributes得到的(是AbstractErrorController的方法),所以我们有以下两种方式;
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面用的数据都是通过errorAttributes.getErrorAttributes得到;容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的; */

//定义的ErrorAttributes
@Component
public class MErrorAttributes extends DefaultErrorAttributes {
	@Override
	public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
	Map<String, Object> map = super.getErrorAttributes(requestAttributes,includeStackTrace);
	map.put("cccc","出错了");
	return map;
}
} 


以上就是Springboot的错误处理机制,如有错误,希望大佬不吝指出

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值