枚举类型与自定义异常

1 篇文章 0 订阅
1 篇文章 0 订阅


注: 个人认为一个项目中,最好有2个自定义异常;一个是 服务 异常,一个是 业务 异常

1、定义响应码与响应消息枚举型

	package com.xxx.xxx;
	
	/**
	 * @Auther: Chengqb
	 * @Date: 2019/6/27 8:40
	 */
	public enum CodeEnum {
	    //请求数据不存在
	    NotData(170003, "请求数据不存在"),  // 枚举:响应码和响应消息;可以有多个
	    AccountIsDisabled(10004, "该账号已被禁用"),
	    ConnectionFailed(170002, "请检查网络连接");
	
	    private Integer code;
	
	    private String msg;
	
	    CodeEnum(Integer code, String msg) {
	        this.code = code;
	        this.msg = msg;
	    }
	
	    public Integer getCode() {
	        return code;
	    }
	
	    public String getMsg() {
	        return msg;
	    }
	}

2、自定义异常

(1)服务异常

	package com.xxx.xxx.xxx.exception;
	
	/**
	 * 服务异常使用
	 * @author Chengqb
	 * @date 2019/6/27 8:41
	 */
	public class ServiceException extends RuntimeException {
	    private Integer code;
	    private String msg;
	
		public ServiceException () {
		        super();
		}
	
		public ServiceException (Integer code) {
	        this.code = code;
	    }
	
		public ServiceException (String msg) {
	        this.msg = msg;
	    }
		    
	    public ServiceException (Integer code, String msg) {
	        this.code = code;
	        this.msg = msg;
	    }
	
	    public Integer getCode() {
	        return this.code;
	    }
	
	    public void setCode(Integer code) {
	        this.code = code;
	    }
	
	    public String getMsg() {
	        return this.msg;
	    }
	
	    public void setMsg(String msg) {
	        this.msg = msg;
	    }
	}

(2)业务异常

package com.xxx.xxx.xxx.exception;

import com.hengan.core.util.ExceptionUtils;

public class BusinessException extends RuntimeException {
    private Integer code;
    private String msg;

	public BusinessException() {
	        super();
	}

	public BusinessException(Integer code) {
        this.code = code;
    }

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

    public Integer getCode() {
        return this.code;
    }

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

    public String getMsg() {
        return this.msg;
    }

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

3、自定义异常使用

   以数据不存在为例,个人认为其归属于业务异常,故使用BusinessException

	if (数据 == null) {
		// 使用BusinessException的两参构造方法,传的参是枚举中的NotData
		throw new BusinessException(CodeEnum.NotData.getCode(), CodeEnum.NotData.getMsg());
	}

   以网络连接失败为例,个人认为其归属于服务异常,故使用ServiceException

	// 使用ServiceException的两参构造方法,传的参是枚举中的NotData
	throw new ServiceException(CodeEnum.ConnectionFailed.getCode(), CodeEnum.ConnectionFailed.getMsg());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值