1)、有模板引擎的情况下;error/状态码;【将错误页面命名为错误状态码.html放在模板引擎文件夹里面的
error文件夹下】,发生此状态码的错误就会来到对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态
码.html);
页面能获取的信息;
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
2)、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
3)、以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
(1)定制自定义的json信息
@ControllerAdvice
public class MyExceptionHandler{
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handleException(Exception e){
Map<String,Object> map=newHashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
//没有自适应效果...
这一步就是请求不管是客户端还是页面都会返回自定义的json数据。(不会自适应
ps:意思就是客户端返回json,页面的返回错误页面)
(2)那怎么办那,我想要定制数据,又想自适应。那就需要把请求转发到/error。
但是转发到/error后 页面并没有转到定制页面,因为status=200 一般做的定制页面只有4xx 5xx之类的。所以要定制自己的错误status
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e,HttpServletRequest request){
Map<String,Object> map=newHashMap<>();
//传入我们自己的错误状态码4xx5xx,否则就不会进入定制错误页面的解析流程
/**
*IntegerstatusCode=(Integer)request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
//转发到/error
return"forward:/error";
}
这个时候又能自适应了,但是仿佛又回到了原点,自适能自适应。我们定制的数据没有带回来,就需要自定义我们的ErrorAttributes
将我们的定制数据携带出去;
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由
getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes{
@Override
public Map<String,Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace){
//获得系统默认的自定义错误信息,
Map<String,Object> map=super.getErrorAttributes(requestAttributes,
includeStackTrace);
//添加一个自定义,错误信息。这样就可以显示出来了
map.put("company","atguigu");
return map;
}
}
这是演示,最后如果要把自定义的信息携带过来,需要在错误处理器里 把错误信息map 添加到request中:
@ExceptionHandler(BindException.class)
public String bindExceptionHandler(BindException bind, HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("code", bind.getErrorCount());
map.put("message", bind.getAllErrors());
request.setAttribute("eto",map);
return "forward:/error";
}
并在自定义的ErrorAttributes中通过webRequest中获取这个属性
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("公司错误信息", "是不是添加成功了");
Map<String,Object> eto = (Map<String, Object>) webRequest.getAttribute("eto", 0);
map.put("eto", eto);
return map;
}
}