异常枚举类:
public enum ErrorCodeEnum {
SYS_ERROR("SYS_ERROR", "系统错误,请重试"),
UNKNOWN_ERROR("UNKNOWN_SYS_ERROR", "未知的系统异常"),
SERVICE_INVOKE_FAIL("SERVICE_INVOKE_FAIL", "服务调用失败"),
ILLEGAL_ARGS("ILLEGAL_ARGS", "参数校验错误"),
;
public static ErrorCodeEnum getByValue(String code) {
for (ErrorCodeEnum result : values()) {
System.out.println(result.ordinal());
if (StringUtils.equals(result.getCode(), code)) {
return result;
}
}
return null;
}
/**
* 结果码值.
*/
private String code;
/**
* 描述.
*/
private String desc;
ErrorCodeEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
自定义异常类:
public class WangException extends RuntimeException {
private static final long serialVersionUID = -8581672033133636908L;
/*** 错误码枚举*/
private ErrorCodeEnum errorCode;
/**
* 详细错误信息
*/
private Map<String, String> errorMap = new HashMap<String, String>();
/**
* 带参构造器.
*
* @param errorCode
*/
public WangException(ErrorCodeEnum errorCode) {
super(errorCode.getDesc());
this.setErrorCode(errorCode);
}
/**
* 带参构造器.
*
* @param errorCode
* @param message
*/
public WangException(ErrorCodeEnum errorCode, String message) {
super(StringUtils.isNotBlank(message) ? message : errorCode.getDesc());
this.setErrorCode(errorCode);
}
/**
* 带参构造器.
*
* @param errorCode
* @param errorMap
*/
public WangException(ErrorCodeEnum errorCode, Map<String, String> errorMap) {
this(errorCode);
this.errorMap = errorMap;
}
/**
* 带参构造器.
*
* @param message
*/
public WangException(String message) {
super(message);
this.setErrorCode(ErrorCodeEnum.UNKNOWN_ERROR);
}
/**
* Gets error code.
*
* @return the error code
*/
public ErrorCodeEnum getErrorCode() {
return errorCode;
}
/**
* Sets error code.
*
* @param errorCode the error code
*/
public void setErrorCode(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}
/**
* Gets error map.
*
* @return the error map
*/
public Map<String, String> getErrorMap() {
return errorMap;
}
/**
* Sets error map.
*
* @param errorMap the error map
*/
public void setErrorMap(Map<String, String> errorMap) {
this.errorMap = errorMap;
}
private static String findMessage(Map<String, String> errorMap) {
if (errorMap.isEmpty()) {
return null;
}
return errorMap.values().iterator().next();
}
}
自定义异常测试类:
public class ExceptionTest {
public static void main(String[] args) {
String name = null;
int i = 0;
try {
if (name == null) {
//throw new TianException(ErrorCodeEnum .ILLEGAL_ARGS);
}
if (i == 0) {
throw new TianException(ErrorCodeEnum .ILLEGAL_ARGS, "参数不能为0");
}
} catch (TianException e) {
System.out.println("异常码:" + e.getErrorCode().getCode());
System.out.println("异常描述:"+e.getMessage());
}
}
}
打印结果: