一、背景:
页面错误:
浏览器访问:
通过请求头访问:
不存在浏览器页面默认效果:
客户端访问:
默认响应Json数据
二、定制错误页面
一、定制错误页面:
1)【重点】有模板引擎的情况下;error/状态码【将错误页面命名为错误状态码,放模板引擎下error文件夹下,错误就会来到对应页面】
2)【重点】可以4xx和5xx作为文件名去匹配(优先寻找精确的状态码.html)
定制内容
展示定制内容:
3)【了解】没有模板引擎的情况(模板引擎找不到这个错误页面),静态资源文件夹下
4)以上都没有错误页面,就是默认来到SpringBoot的默认的错误提示页面
二、定制错误json数据:
1)创建类
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handlerException(Exception e)
{
Map<String,Object> map= new HashMap<>();
map.put("code", "user.notexist");
map.put("message",e.getMessage());
return map;
}
}
缺点没有自适应效果,浏览器和客户端都返回的Json数据,如何变为自适应:
转发到error进行自适应
@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());
//转发error自适应
return "forward:/error";
}
3)将我们的定制数据携带出去
①【复杂】完全来编写一个ErrorController的实现类【编写AbstractErrorController】,放入容器中
②页面上能用的数据或json返回能用的数据通过errorAttributes.getErrorAttributes得到;容器中DefaultErrorAttributes.getErrorAttributes默认进行数据处理
最终的效果:
响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容: