**
*springBoot学习之路之错误处理机制篇
1)springBoot默认的错误处理机制:
浏览器访问:默认效果:返回一个错误的信息页面
客户端访问:如果是其他客户端,默认相应的JSON数据
该类为容器中添加了如下组件:
1.DefaultErrorAttributes
2.BasicErrorController
–处理默认的/error请求
3.ErrorPageCustomizer
–系统出现错误后来到ERROR请求进行处理,;类似spring mvc zhon中定义的 WEB.XML注册的错误页面
4.PreserveErrorControllerTargetClassPostProcessor
步骤:一旦系统出现4xx或者5xx ErrorPageCustomizer来制定相应规则
原理:在ErrorMvcAutoConfiguration:错误的处理机制
2)如何定制错误相应、
1)如何定制错误的页面
** 有模板引擎的情况下,我们直接在error/404.html (/template)
[将错误页面命名为 错误代码.html 放在error文件夹下面]发生此状态码的状态就会来到对应的页面
我们也可以使用4xx和5xx来匹配这种错误来显示,以优先查询精准页面。
页面能获取的信息:
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
**没有引擎模板的情况下,会在静态资源文件夹下,只是没有编译了。
**都找不到的话就会跑到springboot的空白错误页面
2)如何定制错误的json信息格式
写一个异常处理器
第一种
使用 @ControllerAdvice 实现全局异常处理,只需要定义类,添加该注解即可定义方式
@ControllerAdvice
public class MyExceptionHandler {
//浏览器客户端返回的都是json
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handleException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
第二种,转发到/error请求进行自适应效果处理
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message","用户出错啦");
//转发到/error
return "forward:/error";
}
第三种,注册MyErrorAttributes继承自DefaultErrorAttributes(推荐)
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message","用户出错啦");
//将自定义错误数据放入request中
request.setAttribute("ext",map);
//转发到/error
return "forward:/error";
}