文章目录
一、springBoot统一异常处理方式
官网参考地址:https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/htmlsingle/#boot-features-error-handling
搜索关键词:Error Handling
- 方式一 静态异常页面
自定义静态异常页面,又分为两种,第一种 是使用 HTTP 响应码来命名页面,例如 404.html、405.html、500.html …,另一种就是直接定义一个4xx.html,表示400-499 的状态都显示这个异常页面,5xx.html 表示 500-599 的状态显示这个异常页面。
- 在resources目录下新建public目录下添加类似5xx.html自定义渲染页面【官网提供的路径】。
- 在resources目录下新建static目录下添加类似5xx.html自定义渲染页面。
路径:
resources/public/error/5xx.html 或者
resources/static/error/5xx.html
如果两者都存在会先找static目录下的异常,查找顺序。
- 方式二 继承BasicErrorController
整体涉及到的类
- 定义MyErrorController 重写构造方法,重写getErrorAttributes方法
/**
* @ClassName MyErrorController
* @Description 自定义异常
* @Author eastern
* @Date 2019/8/15 下午3:57
* @Version 1.0
**/
public class MyErrorController extends BasicErrorController {
public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorProperties, errorViewResolvers);
}
@Override
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
attrs.remove("timestamp");
attrs.remove("status");
attrs.remove("error");
attrs.remove("path");
String errorCode = attrs.get("message").toString();
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
attrs.put("code", attrs.get("message"));
attrs.put("message", errorEnum.getMessage());
attrs.put("canRetry", errorEnum.isCanRetry());
return attrs;
}
}
- 定义ErrorConfiguration 配置
参看:ErrorMvcAutoConfiguration
/**
* @ClassName ErrorConfiguration
* @Description 错误处理相关类
* @Author eastern
* @Date 2019/8/15 下午4:08
* @Version 1.0
**/
@Configuration
public class ErrorConfiguration {
@Bean
public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, DispatcherServletPath dispatcherServletPath,
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
return new MyErrorController(errorAttributes, serverProperties.getError(), errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
}
- 定义错误枚举
/**
* 错误枚举类
*/
public enum ErrorEnum {
ID_NOT_NULL("0001", "编号不能为空", false),
UNKNOWN("9999", "未知异常", false);
private String code;
private String message;
private boolean canRetry;
ErrorEnum(String code, String message, boolean canRetry){
this.code = code;
this.message = message;
this.canRetry = canRetry;
}
public static ErrorEnum getByCode(String code){
for (ErrorEnum errorEnum: ErrorEnum.values()) {
if(errorEnum.code.equals(code)){
return errorEnum;
}
}
return UNKNOWN;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public boolean isCanRetry() {
return canRetry;
}
}
- 方式三 利用ControllerAdvice
ControllerAdvice在Controller上包了一层,增强的Controller,但是如果ControllerAdvice里再出现异常,会进入到自定义的ErrorController