默认错误处理机制
默认效果:
- 浏览器会返回一个错误页面,404什么的
- 其他客户端会默认响应一个json数据
简易的部分原理:
容器中有以下组件
- DefaultErrorAttributes:帮我们在页面共享信息。
- BasicErrorController:处理默认/error请求。
- ErrorPageCustomizer:系统出现错误以后来到error请求进行处理。
- DefaultErrorViewResolver:对错误页面进行视图解析。
定制错误页面
默认有模板引擎(thymeleaf),这种情况下降错误页面命名为 错误状态吗.html 放在模板引擎文件夹里(thymeleaf是templates),这时候发生此状态码的错误就会来到这个对应的页面。
可以用4xx或5xx作为错误页面来匹配这种类型的错误。精确优先。
页面可以获取的信息:
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
定制错误的json数据
- 自定义一个异常处理类
public class UserNotExistException extends RuntimeException {
public UserNotExistException(){
super("用户不存在");
}
}
- 自定义一个异常处理器,转发给错误处理器,进行自适应效果处理
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
public String handlerException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入自己的错误状态码,否则不会进入定制错误页面的流程
request.setAttribute("javax.servlet.error.status_code", 500);
map.put("code", "user.notexist");
map.put("message", e.getMessage());
request.setAttribute("ext", map);//转发给错误处理器MyErrorAttributes
//转发到/error
return "forward:/error";
}
}
- 自定义ErrorAttributes,进行数据处理,使信息响应在错误页面
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
/**
*
* @param webRequest
* @param includeStackTrace
* @return map 页面和json能获取的字段
*/
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest,includeStackTrace);
map.put("company", "华为");
Map<String, Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
map.put("ext", ext);
return map;
}
}
参考资料
尚硅谷-Spring Boot核心技术-笔记