@Service
public class ExceptionService {
public void throwException(ResultEnum resultEnum) {
throw new MyException(resultEnum);
}
public void throwException(Integer code, String message) {
throw new MyException(code, message);
}
public void throwNullException(Object object, ResultEnum resultEnum) {
if (object == null) {
throw new MyException(resultEnum);
}
}
public void throwNotNullException(Object object, ResultEnum resultEnum) {
if (object != null) {
throw new MyException(resultEnum);
}
}
public void throwNotEqualsException(Object source, Object target, ResultEnum resultEnum) {
if (!source.equals(target)) {
throw new MyException(resultEnum);
}
}
}
public class MyException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public MyException(Integer code, String message) {
super(message);
this.code = code;
}
public MyException(ResultEnum resultEnum) {
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
}
自定义异常
public enum ResultEnum {
RESPONSE_OK(200, "响应正确"),
PARAM_ERROR(20, "参数不正确"),
NO_LOGIN(444, "未登录"),
OLD_PASSWORD_ERROR(555, "旧密码 错误"),
USERNAME_OR_PSW_ERROR(1010, "账号或密码错误"),
CODE_CAN_NOT_EMPTY(1020, "请输入 验证码"),
SESSION_CODE_IS_EMPTY(1030, "请获取 验证码"),
GET_PHONE_CODE_FAIL(1031, "获取验证码失败"),
CODE_ERROR(1040, "验证码 错误"),
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}