用枚举来处理java自定义异常

在系统开发过程中,总少不免要自己处理一些异常信息,然后将异常信息变成友好的提示返回到客户端的这样一个过程,之前都是new一个自定义的异常,当然这个所谓的自定义异常也是继承RuntimeException的,但这样往往会造成异常信息说明不一致的情况,所以就想到了用枚举来解决的办法。

1、先创建一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:

public interface IErrorCode {
	
    public String getErrorCode();
    
    public String getErrorMessage();
    
}

  

2、创建一个枚举,实现IErrorCode里的方法

public enum SysErrorEnums implements IErrorCode {

    /**参数为空*/
    EMPTY_PARAME("A11002","参数为空"),
    /**参数错误*/
    ERROR_PARAME("A11002","参数错误");
    
    private String errorCode;
    private String errorMessage;
    
    private SysErrorEnums(String errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

3、定义一个自定义的异常类 

public class BusinessException extends RuntimeException {
    
    private static final long serialVersionUID = 1L;
    
    private IErrorCode iErrorCode;
    
    private String errorCode;
    private String errorMessage;
    private Map<String, Object> errorData;
        
        public BusinessException(IErrorCode iErrorCode) {
        super();
        this.iErrorCode = iErrorCode;
        this.errorCode = iErrorCode.getErrorCode();
        this.errorMessage = iErrorCode.getErrorMessage();
    }
        
        //其他get、set、构造方法
}

4、代码中抛异常

if(true){
   throw new BusinessException(SysErrorEnums.EMPTY_OBJ);
}

5、可以通过异常拦截器来拦截错误,获取错误后统一格式输出;

这样做的好处是可以高度统一所有异常返回的code及message, 如果需要更改提示信息或代号,只需更改SysErrorEnums即可,并且可以自行添加多个异常枚举文件来分别对应不同的模板异常信息。代码结构简单,清淅。

原文地址:https://www.cnblogs.com/leskang/p/8119099.html