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

    自定义异常

    局部异常

    全局异常

  • 相关阅读:
    返回一个首尾相连的整数数组中最大子数组的和
    《程序员修炼之道——从小工到专家》读后感一
    成功之路,贵在坚持
    有些路走下去会很苦很累,但是不走会后悔
    商品进行倒计时
    Hibernate中HQL函数汇总及获取当前时间进行比较举例
    java类的继承,多态,抽象类与接口
    equals()与 == 比较,hashCode方法
    面向对象基本知识
    命令控制台与java环境配置
  • 原文地址:https://www.cnblogs.com/LQBlog/p/9244777.html
Copyright © 2011-2022 走看看