zoukankan      html  css  js  c++  java
  • Spring Boot-全局异常处理(八)

    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 新建对应的编码的页面

    自定义异常

    局部异常

    全局异常

  • 相关阅读:
    TLE: poj 1011 Sticks
    UVa 116 Unidirectional TSP
    csuoj 1215 稳定排序
    UVa 103 Stacking Boxes
    UVa 147 Dollars
    UVa 111 History Grading
    怎么在ASP.NET 2.0中使用Membership
    asp.net中如何删除cookie?
    ASP.NET中的HTTP模块和处理程序[收藏]
    NET开发中的一些小技巧
  • 原文地址:https://www.cnblogs.com/LQBlog/p/9244777.html
Copyright © 2011-2022 走看看