springBoot自定义封装异常类进行业务处理
自定义异常类
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errcode;
private String errInfo;
private Object object;
/**
*
*/
public CustomException() {
}
/**
*
* @param errcode
* @param errInfo
* @param throwable
*/
public CustomException(String errcode, String errInfo, Throwable throwable) {
super(throwable);
this.errcode = errcode;
this.errInfo = errInfo;
}
/**
*
* @param errcode
* @param errInfo
* @param throwable
*/
public CustomException(String errcode, String errInfo) {
this.errcode = errcode;
this.errInfo = errInfo;
}
@Override
public String toString() {
return "CustomException [errcode=" + errcode + ", errInfo=" + errInfo + "]";
}
public CustomException(String errcode, String errInfo, Object object) {
this.errcode = errcode;
this.errInfo = errInfo;
this.object = object;
}
/**
* @param arg0
*/
public CustomException(String errInfo) {
this.errInfo = errInfo;
}
/**
* @param arg0
*/
public CustomException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public CustomException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public CustomException(ResultTypeEnum resultTypeEnum) {
this.errcode = resultTypeEnum.getCode();
this.errInfo = resultTypeEnum.getDesc();
}
/**
* @return the errcode
*/
public String getErrcode() {
return errcode;
}
/**
* @return the errInfo
*/
public String getErrInfo() {
return errInfo;
}
public Object getObject() {
return object;
}
}
使用方法
方法中只要验证失败或者异常直接抛出,通过catch捕获之后再进行处理,这样的目的是使逻辑更加清晰
@RequestMapping(value = "/private/face/asyncResult", method = {RequestMethod.GET, RequestMethod.POST})
public Object getAsyncFaceAuthResult(HttpServletRequest request) {
RequestResult requestResult = new RequestResult();
requestResult.setCode(ResultTypeEnum.ResultTypeEnum_200.getErrCode());
requestResult.setMessage(ResultTypeEnum.ResultTypeEnum_200.getMessage());
try {
if (
// 条件
) {
// 处理逻辑
} else {
// 验证失败
// 枚举类的封装,参考文章 前后端分离RequestResult返回模型的封装
throw new CustomException(枚举类.枚举名称.getCode(), 枚举类.枚举名称.getMessage());
}
} catch (Exception e) {
if (e instanceof CustomException) {
CustomException customeException = (CustomException) e;
requestResult.setCode(customeException.getCode());
requestResult.setMessage(customeException.getErrInfo());
} else {
// 枚举类的封装,参考文章 前后端分离RequestResult返回模型的封装
requestResult.setCode(ResultTypeEnum.ResultTypeEnum_1001.getErrCode());
requestResult.setMessage(ResultTypeEnum.ResultTypeEnum_1001.getMessage());
}
}
return requestResult;
}