异常统一处理
项目中有负责此方面,最近有空正好总结下,代码为测试代码,非在项目中所写的业务代码,本质相同。
异常抛出及处理流程:
图片百度得来,觉得总结的比较好。
1、在项目抛出自定义异常,springMVC框架抛出框架异常类型
2、统一由异常捕获类捕获异常,并进行处理
3、捕获到自定义异常则直接取出错误代码及错误信息,响应给用户。
4、捕获到非自定义异常类型首先从Map中找该异常类型是否对应具体的错误代码,如果有则取出错误代码和错误信息并响应给用户,如果从Map中找不到异常类型所对应的错误代码则统一为404错误代码并响应给用户。
5、将错误代码及错误信息以Json格式响应给用户。
总结:一句话,捕获的异常能解析则解析,不能解析则统一给个响应码,此响应码对应一个通用错误消息,比如“系统繁忙”,前端拿着此响应码记得给个好点的图,不然会被差评(哈哈哈)。
自定义异常类:
/**
* 描述:
* 自定义异常类
*
* @author XueGuCheng
* @create 2020-02-29 23:06
*/
public class XGCException extends RuntimeException {
private ResultCode resultCode;
public XGCException(ResultCode resultCode){
//异常信息为错误代码 + 异常信息
super("错误代码:"+resultCode.code()+"错误信息:"+resultCode.message());
this.resultCode = resultCode;
}
public ResultCode getResultCode(){
return this.resultCode;
}
}
自定义异常抛出类:
/**
* 描述:
* 自定义异常抛出类
*
* @author XueGuCheng
* @create 2020-02-29 23:09
*/
public class ExceptionCast {
//使用此静态方法抛出自定义异常
public static void cast(ResultCode resultCode){
throw new XGCException(resultCode);
}
}
自定义异常捕获类:
/**
* 描述:
* 自定义异常捕获类
*
* @author XueGuCheng
* @create 2020-02-29 23:12
*/
@ControllerAdvice
public class ExceptionCatch {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
//使用ImmutableMap类型的容器存放异常类型和错误代码的映射:EXCEPTIONS
//ImmutableMap的特点的一旦创建不可改变,并且线程安全
private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
//使用builder来构建一个异常类型和错误代码的异常
protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
//捕获XGCException异常
@ExceptionHandler(XGCException.class)
@ResponseBody
public ResponseResult xGCException(XGCException e) {
LOGGER.error("catch exception : {}\r\nexception: ", e.getMessage(), e);
ResultCode resultCode = e.getResultCode();
ResponseResult responseResult = new ResponseResult(resultCode);
return responseResult;
}
//对Exception异常的捕获
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception exception) {
//记录日志
LOGGER.error("catch exception:{}", exception.getMessage());
if (EXCEPTIONS == null) {
EXCEPTIONS = builder.build();
}
final ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
final ResponseResult responseResult;
if (resultCode != null) {
responseResult = new ResponseResult(resultCode);
} else {
responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
}
return responseResult;
}
static {
//在这里加入一些基础的异常类型判断
builder.put(XXXException.class,Code);
}
}