Springboot错误处理机制实现原理解析

1.默认的错误机制

默认效果

①在浏览器中访问不存在的请求时,springboot默认返回一个空白页面

浏览器的请求头

②客户端访问时,返回json数据

{

"timestamp": "2020-03-24T02:49:56.572+0000",

"status": 404,

"error": "Not Found",

"message": "No message available",

"path": "/"

}

客户端访问的请求头

原理

  可以参照 ErrorMvcAutoConfiguration 错误处理的自动配置

  给容器中添加了以下组件

    1.DefaultErrorAttributes

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;

}

@RequestMapping(

produces = {"text/html"}

)

public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {

HttpStatus status = this.getStatus(request);

//处理页面的请求返回给前台数据 model 的获取 ,调用

Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));

response.setStatus(status.value());

ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);

return modelAndView != null ? modelAndView : new ModelAndView("error", model);

}

//调用 AbstractErrorController#getErrorAttributes

protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {

WebRequest webRequest = new ServletWebRequest(request);

return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);

}

最终调用DefaultErrorAttributes#getErrorAttributes

public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {

    2.BasicErrorController : 处理默认的 /error 请求

@Controller

@RequestMapping({"${server.error.path:${error.path:/error}}"})

public class BasicErrorController extends AbstractErrorController {

private final ErrorProperties errorProperties;

public String getErrorPath() {

return this.errorProperties.getPath();

}

@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.isIncludeStackTrace(request, MediaType.TEXT_HTML)));

response.setStatus(status.value());

  //去哪个页面作为错误页面,包括页面地址和内容

ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);

return modelAndView != null ? modelAndView : new ModelAndView("error", model);

}

@RequestMapping //产生json类型的数据, 其他客户端发送的请求来到这个方法处理

public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

HttpStatus status = this.getStatus(request);

if (status == HttpStatus.NO_CONTENT) {

return new ResponseEntity(status);

} else {

Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));

return new ResponseEntity(body, status);

}

}

                 3.ErrorPageCustomizer

public class ErrorProperties {

@Value("${error.path:/error}")

private String path = "/error"; //系统出现错误请求之后来到 /error 请求进行处理 ,(类似于以前 web.xml 中注册的错误页面规则)

    4.DefaultErrorViewResolver

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);

}

return modelAndView;

}

private ModelAndView resolve(String viewName, Map<String, Object> model) {    //默认 springboot 可以找到这个页面 error/404

String errorViewName = "error/" + viewName;    //模板引擎可以解析这个页面地址就用模板引擎解析

TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);    //模板引擎可用的情况下就返回到 errorViewName 指定的视图地址

return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);

}

  //模板引擎不可用就在静态资源文件夹里面找 errorViewName 对应的页面 error/404.html

private ModelAndView resolveResource(String viewName, Map<String, Object> model) {

String[] var3 = this.resourceProperties.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;

}

    步骤:

      一旦系统出现 4xx 或者 5xx 之类的错误,ErrorPageCustomizer 就会生效(定制错误的响应规则),就会来到 /error 请求,会被BasicErrorController

处理。

①响应页面 去哪个页面由 DefaultErrorViewResolver 决定

protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {

Iterator var5 = this.errorViewResolvers.iterator();     //解析所有的 ErrorViewResolver 得到 modelAndView

ModelAndView modelAndView;

do {

if (!var5.hasNext()) {

return null;

}

ErrorViewResolver resolver = (ErrorViewResolver)var5.next();

modelAndView = resolver.resolveErrorView(request, status, model);

} while(modelAndView == null);

return modelAndView;

}

2.错误信息的定制

①如何定制错误页面

  1>有模板引擎的情况下: error/状态码 ;【将错误页面命名为 错误码.html 放在模板引擎文件夹下的 error 文件夹下】,发生此状态码的错误就来到

  对应的页面;

我们可以使用 4xx 和 5xx 作为错误页面的文件名来匹配这种类型的所欲错误,精确优先(优先寻找精确的 状态码.html );

  页面能够获取到的信息

      timestamp :时间戳

      status : 状态码

      exception : 异常对象

      message : 异常消息

      errors : JSR303数据校验的错误都在这儿

    2>.没有模板引擎(模板引擎找不到这个页面),静态资源文件夹下找

    3>.以上都没有错误页面,就默认来到 springboot 默认的错误页面

②、自定义异常处理&返回定制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;

}

}

//通过异常处理器,但没有自适应效果(浏览器返回页面,客户端访问返回json数据)

2)、转发到/error进行自适应响应效果处理

@RequestMapping(

produces = {"text/html"}

)

public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {     //获取错误的状态码,在分析的过程中,要注意参数从哪儿来? =======》前领导的一句话,哈哈……

HttpStatus status = this.getStatus(request);

Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));

response.setStatus(status.value());    //依据错误状态码解析错误试图,如果直接转发,不指定错误状态码则试图解析出错(直接转发状态码为 200 ,到不了定制的 4xx 5xx 的页面)

ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);

return modelAndView != null ? modelAndView : new ModelAndView("error", model);

}

@ExceptionHandler(UserNotExistException.class)

public String handleException(Exception e, HttpServletRequest request){

Map<String,Object> map = new HashMap<>();

<span>//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程</span>

/**

* 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());

//转发到/error

return "forward:/error";

}

3)、将我们的定制数据携带出去;======》即修改model中的值即可

出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);

1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;

2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;

容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;

自定义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;

}

}

最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,

以上是 Springboot错误处理机制实现原理解析 的全部内容, 来源链接: utcz.com/z/328080.html

回到顶部