在后端发生异常或者是请求出错时,前端通常显示如下
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 07 15:38:07 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
对于用户来说非常不友好。
本文主要讲解如何在基础框架中实现统一异常处理功能。
实现方式
1.编写统一返回类CommonResponse
通过统一返回结果,使得前端在接受到返回参数时,可以进行统一处理
public class CommonResponse<T> {
/**
* 成功码
*/
private static final String SUCCESS="0";
/**
* 不加密
*/
private static final Integer NO_ENCRYPT=0;
@ToString
public static class Header{
/**
* 版本
*/
String version;
/**
* 应答码,0 代表成功,失败则填写异常错误码
*/
String responseCode;
/**
* 消息
*/
String message;
/**
* 加密标志,1标记加密,0不加密 默认不加密为0
*/
Integer encryptFlag;
}
private Header header;
/**
* VO对象
*/
private T body;
}
2.编写自定义异常码
通过枚举类型,列举一系列的通用异常码、业务异常码等,其中包括异常的编码,和错误信息。
public enum CommonErrorCode {
SUCCESS("0",
"成功~"),
/**
* 404 Web 服务器找不到您所请求的文件或脚本。请检查URL 以确保路径正确。
*/
NOT_FOUND("404",
String.format("哎呀,无法找到这个资源啦(%s)", HttpStatus.NOT_FOUND.getReasonPhrase())),
/**
* 405 对于请求所标识的资源,不允许使用请求行中所指定的方法。请确保为所请求的资源设置了正确的 MIME 类型。
*/
METHOD_NOT_ALLOWED("405",
String.format("请换个姿势操作试试(%s)", HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase())),
/**
* 415 Unsupported Media Type
*/
UNSUPPORTED_MEDIA_TYPE("415",
String.format("呀,不支持该媒体类型(%s)", HttpStatus.UNSUPPORTED_MEDIA_TYPE.getReasonPhrase())),
/**
* 系统异常 500 服务器的内部错误
*/
EXCEPTION("500", "服务器开小差,请稍后再试"),
DATA_INTEGRITY_VIOLATION_EXCEPTION("50001", "该操作违反了完整性"),
MYBATIS_SYSTEM_EXCEPTION("50002", "数据库未连接,请稍后再试"),
NULL_POINTER_EXCEPTION("50003","操作空数据变量"),
/**
* 系统限流
*/
TRAFFIC_LIMITING("429", "哎呀,网络拥挤请稍后再试试"),
/**
* 服务调用异常
*/
API_GATEWAY_ERROR("9999", "网络繁忙,请稍后再试"),
/**
* 参数错误
*/
PARAM_ERROR("100", "参数错误"),
/**
* 业务异常
*/
BUSINESS_ERROR("400", "业务异常"),
/**
* rpc调用异常
*/
RPC_ERROR("510", "呀,网络出问题啦!");
/**
* 异常码
*/
private String code;
/**
* 异常信息
*/
private String message;
CommonErrorCode(String code, String message) {
this.code = code;
this.message = message;
}
}
3.编写自定义异常类
异常类继承了运行时异常,并定义了异常码和异常信息,并且可以通过自定义异常码进行初始化
public class AppException extends RuntimeException {
/**
* 异常码
*/
String code;
/**
* 异常信息
*/
String message;
public AppException() {
}
public AppException(CommonErrorCode commonErrorCode){
this.code = commonErrorCode.getCode();
this.message = commonErrorCode.getMessage();
}
public AppException(BusinessErrorCode businessErrorCode){
this.code = businessErrorCode.getCode();
this.message = businessErrorCode.getMessage();
}
public AppException(SystemErrorCode systemErrorCode){
this.code = systemErrorCode.getCode();
this.message = systemErrorCode.getMessage();
}
public AppException(String code, String message){
this.code = code;
this.message = message;
}
}
4.编写统一异常处理类
@RestControllerAdvice 是组件注解,他使得其实现类能够被classpath扫描自动发现,如果应用是通过MVC命令空间或MVC Java编程方式配置,那么该特性默认是自动开启的。
@Slf4j为日志注解,在捕获到异常时进行日志的记录
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* NoHandlerFoundException 404 异常处理
*/
@ExceptionHandler(value = NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.OK)
public CommonResponse handlerNoHandlerFoundException(NoHandlerFoundException exception) {
outPutErrorWarn(NoHandlerFoundException.class, CommonErrorCode.NOT_FOUND, exception);
return CommonResponse.error(CommonErrorCode.NOT_FOUND);
}
/**
* 输出日志
* @param errorType
* @param secondaryErrorType
* @param throwable
*/
public void outPutErrorWarn(Class errorType, Enum secondaryErrorType, Throwable throwable) {
log.warn("[{}] {}: {}", errorType.getSimpleName(), secondaryErrorType, throwable.getMessage());
}
}
5.编写注解类
/**
* @Description: 统一异常处理注解
* @Author: zerui.zheng
* @Date: 2019/12/5 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(GlobalExceptionHandler.class)
public @interface EnableGlobalExceptionHandler {
}
基础框架中的统一异常处理编写完成,在项目中只需引用基础框架,并在启动类上使用@EnableGlobalExceptionHandler注解,即可实现统一异常处理功能。