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";
}
浏览器:(此时是自定义的错误页面)
其他:

猜你喜欢

转载自www.cnblogs.com/Mrchengs/p/10357010.html
今日推荐