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

    自定义异常

    局部异常

    全局异常

  • 相关阅读:
    golang批量修改文件名
    golang执行带空格的cmd命令
    了解golang的可变参数(... parameters)
    ADB命令连接逍遥模拟器
    通达信如何批量导出自定义板块,以及定义常量
    通达信日K线图中取周K线指标值
    go读取通达信本地数据
    Python读取通达信本地数据
    Golang: 解析JSON数据之一
    MT【357】角度的对称性
  • 原文地址:https://www.cnblogs.com/LQBlog/p/9244777.html
Copyright © 2011-2022 走看看