/**
* 异常工具类
*/
public class CCException extends RuntimeException {
private Throwable t;
private String errorCode;
public CCException(String message) {
super(message);
}
public CCException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public CCException(String errorCode, String message, Throwable t) {
super(message);
this.errorCode = errorCode;
this.t = t;
}
public CCException(ErrorCodeEnum errorEnum) {
super(errorEnum.getDesc());
this.errorCode = errorEnum.getCode();
}
public CCException(ErrorCodeEnum errorEnum, String message) {
super(message);
this.errorCode = errorEnum.getCode();
}
public CCException(ErrorCodeEnum errorEnum, Throwable t) {
super(errorEnum.getDesc());
this.errorCode = errorEnum.getCode();
this.t = t;
}
/**
* Getter method for property <tt>t</tt>.
*
* @return property value of t
*/
public Throwable getT() {
return t;
}
/**
* Setter method for property <tt>t</tt>.
*
* @param t value to be assigned to property t
*/
public void setT(Throwable t) {
this.t = t;
}
/**
* Getter method for property <tt>errorCode</tt>.
*
* @return property value of errorCode
*/
public String getErrorCode() {
return errorCode;
}
/**
* Setter method for property <tt>errorCode</tt>.
*
* @param errorCode value to be assigned to property errorCode
*/
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
ErrorCodeEnum 中定义业务相关异常code
对异常进行分类
- 系统异常: 这类异常通常是大致地提示使用方系统不可用,同时需要相关人员更进处理的
- 非系统异常:这类异常通常是一些义务逻辑而已,比如检查到用户参数有误后抛出的异常
【异常分类原则】:先明确定义好什么样的系统属于系统异常,什么样的异常属于自定义异常,当捕获到一个异常或产生错误时,看这个异常是哪种场景,然后在归类。
异常使用规范:
- 在可能发生异常的地方(调用第三方服务、IO操作、类型转换、参数校验、db操作、定时任务等),不能直接抛出异常,需要使用具体的异常错误码,将错误信息及主要参数进行抛出,同时打印错误日志,在接口最外层捕获异常;
- 在异常的errorMessage中,需要写明具体的接口名,方法名,主要参数code及value
- try-catch的范围尽可能小,尽量只针对非稳定代码进行try-catch
- 在finally中一定要将资源对象、流对象闭,如果try中包含事物,需要将其回滚
- 当我们捕获到一个依赖方的异常时,需要判断这个异常级别应该对应于我们系统已经定义的哪个异常