模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹即templates里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
#获取错误信息server.error.include-exception=trueserver.error.include-message=always
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h1>status:[[${status}]]</h1>//行内写法
<h1>timestamp:[[${timestamp}]]</h1>
<h1>error:[[${error}]]</h1>
<h1>exception:[[${exception}]]</h1>
<h1>message:[[${message}]]</h1>
<h1>message:[[${ext.code}]]</h1>
</main>
@ControllerAdvice //异常处理 标注MyExceptionHandler.Class 为异常处理类
@ControllerAdvice //异常处理
public class MyExceptionHandler {
//第一种:浏览器客户端都是返回json数据
// @ResponseBody //将数据json格式发送到页面显示
// @ExceptionHandler(UserNotExistException.class)//指定处理的异常
// public Map<String,Object> handleException(Exception e){
// Map<String,Object> map = new HashMap<>();
// map.put("code","user not");
// map.put("message",e.getMessage());
// return map;
// }
//第二种:浏览器返回页面,客户端返回json数据
@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");
*/
//指定错误码为500触发相应的错误页面及设定的参数
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
request.setAttribute("ext",map);
//转发到/error
return "forward:/error";
}
}
@Component 相当于加入一个ben到容器中 标注 MyErrorAttributes.Class中
//给容器中加入自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> map = super.getErrorAttributes(webRequest, options);
map.put("company","atguigu");//公司名称atguigu
//我们的异常处理器携带的数据
Map<String,Object> ext = (Map<String,Object>)webRequest.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}