自定义异常处理
这两天在构建一个公共模块,调用之后进行异常处理的逻辑
public class ApiException extends RuntimeException {
private IErrorCode errorCode;
public ApiException(IErrorCode errorCode){
super(errorCode.getDesc());
fillInStackTrace();
this.errorCode = errorCode;
}
public IErrorCode getErrorCode(){
return this.errorCode;
}
}
public interface IErrorCode {
Long getCode();
String getDesc();
}
public enum ErrorCode implements IErrorCode{
SUCCESS(0L,"ok"),
NOT_FOUND(10000L,"source not found");
private Long code;
private String desc;
ErrorCode(Long code,String desc){
this.code = code;
this.desc = desc;
}
@Override
public Long getCode(){
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
public static ErrorCode getErrorCodeByCode(Long code){
for (ErrorCode errorCode : ErrorCode.values()){
if (errorCode.code.equals(code)){
return errorCode;
}
}
return null;
}
}
调用的方法举例:
Optional<T> optional=list.stream.filter(...).findAny();
if(!optional.isPresent()){
throw new ApiException(ErroCode.NOT_FOUND);
}