- 通过继承
DefaultErrorAttributes
来实现自定义异常数据 2.3.0之前
我们通过覆写 getErrorAttributes(WebRequest webRequest, boolean includeStackTrace)
来实现,但该方法已被废弃2.3.0之后
我们通过覆写 getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options)
来实现- 示例:
@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.forEach((k, v) -> {
System.out.println("key: " + k + " value: " + v);
});
if ((Integer)map.get("status") == 404) {
return Map.of("code", 404, "message", "页面不存在");
}
return map;
}
}