欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

再谈java自定义异常(Exception)

程序员文章站 2024-03-20 18:51:04
...

再谈java自定义异常(Exception)

java学习书籍上,必然对java异常进行很详细的介绍,这里笔者不必再累述;如今分布式系统设计已经深入普及到我们工作挡住,随着系统的服务逐渐模块化,业务的复杂度日益增加,那么对异常的处理即打印异常到客户端,就显得十分重要了,项目研发过程中,兄弟们的资质参差不齐,所以,对异常的封装也是必不可少的工作。

这里,笔者谈谈自己的异常设计感受,当然如果有更好的设计思想与实践,也可与笔者一同分享。

首先,我们应该分两大异常类:

    1、系统异常

    2、业务异常

毋庸置疑,系统异常也就是因程序不健壮或者因为数据影响引发的异常,是本服务抛出的,与外界服务、系统没有关系

一、创建系统异常类:SysException

/**
 * @ClassName SysException
 * @Description 系统异常
 * @author jrlisheng5
 * @Date 2016年6月14日 下午2:41:29
 * @version 1.0.0
 */
public class SysException extends Exception {

    private static final long serialVersionUID = -4742832112872227456L;
    /**系统错误码*/
    private String code;
    /**错误描述*/
    private String msg;
    
    public SysException() {
        super();
    }
    public SysException(Throwable t) {
        super(t);
    }
    public SysException(String code, String msg) {
        super(code + '|' + msg);
        this.code = code;
        this.msg = msg;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}


业务异常,又可能是服务A、服务B,外界系统A、外界系统B,抛给客户端某个请求的,所有区别于系统的设计是,多了外界异常 描述

一、创建业务异常类:ServiceException


/**
 * @ClassName ServiceException
 * @Description 业务异常
 * @author jrlisheng5
 * @Date 2016年6月14日 下午2:47:16
 * @version 1.0.0
 */
public class ServiceException extends RuntimeException {
	private static final long serialVersionUID = -4742832112872227456L;
	/**系统错误码*/
	private String code;
	/**错误描述*/
	private String msg;
	/**外部错误码*/
	private String logMsg;
	
	public ServiceException() {
		super();
	}
	public ServiceException(Throwable t) {
		super(t);
	}
	
	public ServiceException(String code, String msg) {
		super(code + '|' + msg);
		this.code = code;
		this.msg = msg;
	}
	public ServiceException(String code, String msg, String logMsg) {
		super(code + '|' + msg +  '|' + logMsg);
		this.code = code;
		this.msg = msg;
		this.logMsg = logMsg;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getLogMsg() {
		return logMsg;
	}
	public void setLogMsg(String logMsg) {
		this.logMsg = logMsg;
	}
	
	@Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}

短信验证码验证失败异常,即业务异常

三、定义短信验证异常类

/**
 * @ClassName SmsValidatorException
 * @Description 短信验证异常
 * @author jrlisheng5
 * @Date 2016年6月14日 下午3:13:13
 * @version 1.0.0
 */
public class SmsValidatorException extends ServiceException {

	private static final long serialVersionUID = -647562559025214578L;

	private String smsVerfifyCode;

	public SmsValidatorException() {
		super();
	}

	public SmsValidatorException(String code, String msg,String smsVerfifyCode) {
		super(code, msg);
		this.smsVerfifyCode = smsVerfifyCode;
	}

	public SmsValidatorException(String code, String msg, String logMsg,String smsVerfifyCode) {
		super(code, msg, logMsg);
		this.smsVerfifyCode = smsVerfifyCode;
	}

	public String getSmsVerfifyCode() {
		return smsVerfifyCode;
	}

	public void setSmsVerfifyCode(String smsVerfifyCode) {
		this.smsVerfifyCode = smsVerfifyCode;
	}

	@Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }

有异常抛出的时候,将异常系统反馈给客户端

四、客户端异常反馈类:ClientResponse<T>

/**
 * @Package com.jd.jr.fp.front.domain.response
 * @ClassName AppResponse
 * @Description. 客户端消息反馈对象
 * @author lisheng
 * @Date. 2016年6月14日 下午2:51:49
 * @version 1.0.0
 * @param <T>
 */
public class ClientResponse<T> {

    private static final int SUCCESS_CODE = 0;
    /** 异常编号 */
    private static final int FIAL_CODE = -1;
    /** 未登录 */
    private static final int NOT_LOGIN_CODE = -2;
    /** 未授权 */
    private static final int NOT_REALNAME_CODE = -3;

    private int resultCode;

    private Result resultMsg;

    private T resultData;

    public ClientResponse() {
    }

    public ClientResponse(int resultCode) {
        this.resultCode = resultCode;
    }

    public ClientResponse(int resultCode, String code, String msg) {
        this.resultCode = resultCode;
        this.resultMsg = new Result(code, msg);
    }

    public ClientResponse(int resultCode, T resultData) {
        this.resultCode = resultCode;
        this.resultData = resultData;
    }

    public int getResultCode() {
        return resultCode;
    }

    public Result getResultMsg() {
        return resultMsg;
    }

    public T getResultData() {
        return resultData;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }

    public static <T> ClientResponse<T> respSuccess(T respDate) {
        return new ClientResponse<T>(SUCCESS_CODE, respDate);
    }

    public static <T> ClientResponse<T> respFail() {
        return new ClientResponse<T>(FIAL_CODE, "-1", "系统运维中,请稍后再试。");
    }

    public static <T> ClientResponse<T> respFail(String code, String msg) {
        return new ClientResponse<T>(FIAL_CODE, code, msg);
    }

    public static <T> ClientResponse<T> respLoginFail() {
        return new ClientResponse<T>(NOT_LOGIN_CODE);
    }

    public static <T> ClientResponse<T> respRealNameFail(T respDate) {
        return new ClientResponse<T>(NOT_REALNAME_CODE, respDate);
    }

    /**
     * 错误码对象
     * 
     * @author lisheng
     * @date 2016-5-18 09:29:26
     */
    public class Result {

        private String code;

        private String msg;

        public Result() {

        }

        public Result(String code, String msg) {
            this.code = code;
            this.msg = msg;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        @Override
        public String toString() {
            return ReflectionToStringBuilder.toString(this);
        }
    }
}

将返回对象反馈到客户端

五、定义测试案例:

        @RequestMapping("init")
	@ResponseBody
	public ClientResponse<InitRespVo> init(@RequestBody InitReqVo reqVo, HttpServletRequest request) {
		try {
			logger.infof("init req:", reqVo.toString());
			InitRespVo result = service.init(reqVo);
			logger.infof("init resp:",result.toString());
			return ClientResponse.respSuccess(result);
		} catch (AppException e) {
			logger.error("/init fail:",e.getLogDesc());
			return ClientResponse.respFail(String.valueOf(e.getCode()), e.getLogDesc());
		} catch (Exception e) {
			logger.error("/FixedredeemPayCtrl.init error:",e);
			return ClientResponse.respFail();
		}
	}