枚举类型与自定义异常目录
注: 个人认为一个项目中,最好有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());