1、创建通用错误接口:CommonError
public interface CommonError {
public int getErrorCode();
public String getErrorMsg();
public CommonError setErrorMsg(String errorMsg);
}
2、创建实现类:EmBusinessError
public enum EmBusinessError implements CommonError {
//通用错误类型10001
PARAMETER_VALIDATION_ERROR(10001,"参数不合法"),
UNKNOWN_ERROR(10002,"未知错误"),
//例:2000开头为用户信息相关错误定义
USER_NOT_EXIST(20001,"用户不存在"),
USER_LOGIN_FAIL(20002,"用户手机号或密码不正确")
;
private int errprCpde;
private String errorMsg;
private EmBusinessError(int errorCode, String errorMsg) {
this.errprCpde = errorCode;
this.errorMsg = errorMsg;
}
@Override
public int getErrorCode() {
return this.errprCpde;
}
@Override
public String getErrorMsg() {
return this.errorMsg;
}
@Override
public CommonError setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
return this;
}
}
3、创建包装器业务异常类实现 :BusinessException 继承 Exception
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
//直接接收EmBusinessError的传参用于构造业务异常
public BusinessException (CommonError commonError){
super();
this.commonError = commonError;
}
//接收自定义errorMsg的方式构造业务异常
public BusinessException(CommonError commonError,String errorMsg){
super();
this.commonError = commonError;
this.commonError.setErrorMsg(errorMsg);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrorMsg() {
return this.commonError.getErrorMsg();
}
@Override
public CommonError setErrorMsg(String errorMsg) {
this.commonError.setErrorMsg(errorMsg);
return this;
}
}
后记 .
关于如何调用异常处理工具类的问题,非常简单,我就先写一个例子在下面,仅供参考
//假如登录时,通过账号密码查询用户不存在
if(user == null){
throw new BusinessException(EmBusinessError.USER_NOT_EXITS);
}
//也可通过 BusinessException.setErrorMsg()自定义错误信息
if(user == null){
throw new BusinessException(EmBusinessError.USER_NOT_EXITS,"请检查用户名密码是否正确");
}
如果项目是Java web,那么Controller也会用上,写一个BaseController,每一个Controller都继承它
public class BaseController {
public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";
//定义exceptionhandler解决未被controller层吸收的exception
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request, Exception ex){
Map<String,Object> responseData = new HashMap<>();
if(ex instanceof BusinessException){
BusinessException businessException = (BusinessException)ex;
responseData.put("errorCode",businessException.getErrorCode());
responseData.put("errorMsg",businessException.getErrorMsg());
}else{
responseData.put("errorCode", EmBusinessError.UNKNOWN_ERROR.getErrorCode());
responseData.put("errorMsg",EmBusinessError.UNKNOWN_ERROR.getErrorMsg());
}
return CommonRetrunType.create(responseData,"fail");
}
}