zoukankan      html  css  js  c++  java
  • 15、SpringBoot-CRUD错误处理机制(2)

    二、如何定制错误响应

    1).如何定义错误处理页面

    1.1、有模板引擎的情况下;error/状态码; 
           【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件夹下】
            发生此状态码的错误就会来到 对应的页面;

       

            可以使用4xx、5xx作为错误页面的文件名来匹配这种类型的所有错误
            精确优先(优先寻找精确的状态码.html);
            页面能获取的信息( DefaultErrorAttributes)
                timestamp:时间戳
                status:状态码
                error:错误提示
                exception:异常对象
                message:异常消息
                errors:JSR303数据校验的错误都在这里

        

       

       

      

       1.2、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件下找
     
       1.3、默认以上两中都没有的时候,默认来到springboot的默认页面

       

     2)、定制json数据

     设置user异常

    public class UserException extends RuntimeException {
        public UserException() {
            super("the user is not exist!");
        }
    }

    异常页面:

    <h1>status:[[${status}]]</h1>
    <h1>timestamp:[[${timestamp}]]</h1>
    <h1>error:[[${error}]]</h1>
    <h1>message:[[${message}]]</h1>

     如果此时浏览器访问报错:

     其他客户端的访问:

     

    2.1、自定义异常处理返回json数据
    没有自适应效果
    @ControllerAdvice
    public class MyException  {
        @ResponseBody
        @ExceptionHandler(UserException.class)
        public Map<Object,String> userExc(Exception e){
            Map<Object,String> map = new HashMap<>();
            map.put("code","user.not.exist");
            map.put("message",e.getMessage());
            return map;
        }
    
    }

    其他客户端的访问:

    浏览器的访问:

     

    2.2、转发到/error进行自适应响应效果处理
    @ExceptionHandler(UserException.class)
    public String userExc(Exception e){
        Map<Object,String> map = new HashMap<>();
        map.put("code","user.not.exist");
        map.put("message",e.getMessage());
        return "forward:/error";
    }

    其他客户端:

    浏览器:(此时是系统默认的处理页面)

     

    在对代码进行改动

    @ExceptionHandler(UserException.class)
    public String userExc(Exception e, HttpServletRequest request){
        Map<Object,String> map = new HashMap<>();
    
        //传入我们自己的错误状态码  4xx  5xx
        //否则就不会进入定制错误页面的解析流程
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",400);
    
        //此时的数据是无法携带出去的
        map.put("code","user.not.exist");
        map.put("message",e.getMessage());
        return "forward:/error";
    }
    浏览器:(此时是自定义的错误页面)
    其他:
  • 相关阅读:
    浅析Vue Router中关于路由守卫的应用以及在全局导航守卫中检查元字段
    react-native 项目配置ts运行环境
    #mobx应用在rn项目中
    react-native TextInput输入框输入时关键字高亮
    react-native-亲测可用插件
    nodejs+express实现图片上传
    cordova图片上传,视频上传(上传多个图片,多个视频)
    cordova图片上传,视频上传(上传单个图片,单个视频)
    移动端如何测试(前端,cordova)
    在mac上将apk包安装到android手机上
  • 原文地址:https://www.cnblogs.com/Mrchengs/p/10357010.html
Copyright © 2011-2022 走看看