1、错误页面:
将4xx.html或者5xx.html 页面放到静态资源路径下的/error/文件夹中,如:classpath:/static/error/4xx.html,发生状态码为4xx (404、400等)的错误时,自动跳转到该页面。
静态文件有以下几个默认路径:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
2、全局异常处理:
@ControllerAdvice
public class ExceptionController{
@ExceptionHandler(Exception.class)
public Map<String,Object> dealWithException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("status",500);
map.put("msg",e.getMessage());
return map;
}
}
3、返回自定义404错误的json数据:
1.完全自定义Springboot错误处理器:实现ErrorController;
2.部分自定义Springboot错误处理器:继承AbstractErrorController
ps:用它们来替换默认的BasicErrorController处理器
或者:
继承DefaultErrorAutubute重写getErrorAttubutes(),调用父类方法得到错误字段,可获取的信息有:
timestamp:时间
message:错误信息
status:状态字
error:报错信息(类型)
path:路径
ps:可结合1、2、3个步骤,在2中将错误转发到默认处理“forward:/error”,实现自适应切换自定义错误页面和自定义json响应方式的切换。
(个人笔记)