自定义异常:
public interface ExceptionEnums {
public int getCode();
public String getMessage();
}
枚举实现:
public enum DBExceptionEnums implements ExceptionEnums{
UNIQUE_KEY(10001, "主键约束错误");
public int code;
public String message;
private UserEnums(int code, String message){
this.code = code;
this.message = message;
}
@Override
public int getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
自定义异常:
public class ServiceException extends RuntimeException{
private ExceptionEnums exceptionEnums;
public ServiceException(ExceptionEnums exceptionEnums){
this.exceptionEnums = exceptionEnums;
}
public ExceptionEnums getExceptionEnums(){
return exceptionEnums;
}
.....其它get/set方法
}
抛异常:
if(true){
throw new ServiceException(DBExceptionEnums.UNIQUE_KEY);
}
try{
}catch(ServiceException se){
logger.dubug(se.getMessage, se);
return buildExceptionJSON(se); //返回异常JSON
}
private String buildExceptionJSON(ServiceException se){
ExceptionEnums enums = se.getExceptionEnums();
return "{'code':"+ enums.getCode+",'message':' "+enums.getMessage()+"'}";
}