最近突然想到对常见异常进行一各规范的写法
废话不多说 上代码
使用枚举定义异常
import org.apache.commons.lang3.StringUtils;
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;
}
}
定义一个异常类
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class WangException extends RuntimeException {
private static final long serialVersionUID = -8581672033133636908L;
/*** 枚举异常类*/
private ErrorCodeEnum errorCode;
private Map<String, String> errorMap = new HashMap<String, String>();
public WangException(ErrorCodeEnum errorCode) {
super(errorCode.getDesc());
this.setErrorCode(errorCode);
}
public WangException(ErrorCodeEnum errorCode, String message) {
super(StringUtils.isNotBlank(message) ? message : errorCode.getDesc());
this.setErrorCode(errorCode);
}
public WangException(ErrorCodeEnum errorCode, Map<String, String> errorMap) {
this(errorCode);
this.errorMap = errorMap;
}
public WangException(String message) {
super(message);
this.setErrorCode(ErrorCodeEnum.UNKNOWN_ERROR);
}
public ErrorCodeEnum getErrorCode() {
return errorCode;
}
public void setErrorCode(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}
public Map<String, String> getErrorMap() {
return errorMap;
}
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();
}
}
测试
package com.basecode.wtbasecode.Exception.wangException;
public class test {
public static void main(String[] args) {
String name="";
int i=0;
try {
if (name == null)
throw new WangException(ErrorCodeEnum.ILLEGAL_ARGS);
if(i==0)
throw new WangException(ErrorCodeEnum.ILLEGAL_ARGS,"参数不能为0");
}catch (WangException e){
e.printStackTrace();
System.out.println("异常码:"+e.getErrorCode().getCode());
System.out.println("异常描述:"+e.getMessage());
}
}
}
结果: