首页 > 编程语言 > 详细

Spring Boot-全局异常处理(八)

时间:2018-06-29 18:22:31      阅读:177      评论:0      收藏:0      [点我收藏+]

SpringBoot默认异常默认处理机制

Spring boot错误异常时通过BasicErrorController来处理的

通过判断是浏览器请求还是ajax请求响应页面或者json

BasicErrorController部分源码

@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());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null ? modelAndView : new ModelAndView("error", model);
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);
        return new ResponseEntity(body, status);
    }

可以看到 只要是发生生异常浏览器请求 都会默认返回error页面

技术分享图片

覆盖springboot默认异常处理的异常页面

1.在resources/templates 下新增一个error html则可以对默认的error进行覆盖

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
动态error错误页面
<p th:text="${error}"></p>
<p th:text="${status}"></p>
<p th:text="${message}"></p>
</body>
</html>

发生错则打印

技术分享图片

2.如果想对异常进行更细的划分 比如404 跳转到404的错误页面 500跳转到500的错误页面 

只需要在resources/templates/error 新建对应的编码的页面

技术分享图片

自定义异常

局部异常

全局异常

 

Spring Boot-全局异常处理(八)

原文:https://www.cnblogs.com/LQBlog/p/9244777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!