SpringBoot:自定义异常
我们在实现自定义异常的时候,我们需要继承 RuntimeException ,参考代码:
/**
* <b>Function: </b> todo
*
* @program: BizException
* @Package: com.kingbal.king.common.core.exception
* @author: dingcho
* @date: 2024/09/14
* @version: 1.0
* @Copyright: 2024 www.kingbal.com Inc. All rights reserved.
*/
public class BizException extends RuntimeException{
private static final long serialVersionUID = 9104770577278712502L;
/**
* 状态码
*/
private int code;
private ErrorCodeEnum errorEnum;
public BizException(ErrorCodeEnum errorEnum, Throwable cause) {
super(errorEnum.getMsg(), cause);
this.code = errorEnum.getCode();
this.errorEnum = errorEnum;
}
public BizException(ErrorCodeEnum errorEnum) {
super(errorEnum.getMsg());
this.code = errorEnum.getCode();
this.errorEnum = errorEnum;
}
public BizException(ErrorCodeEnum errorEnum, String message) {
super(message);
this.code = errorEnum.getCode();
this.errorEnum = errorEnum;
}
}
/**
* <b>Function: </b> todo
*
* @program: ErrorCodeEnum
* @Package: com.kingbal.king.common.core.constant.enums
* @author: dingcho
* @date: 2024/09/14
* @version: 1.0
* @Copyright: 2024 www.kingbal.com Inc. All rights reserved.
*/
@Getter
@AllArgsConstructor
public enum ErrorCodeEnum {
BIZ_PARAM_ERROR(400,"非法的参数!"),
;
/**
* 类型
*/
private final Integer code;
/**
* 描述
*/
private final String msg;
}
使用:
// 调用
throw new BizException(ErrorCodeEnum.BIZ_PARAM_EROOR);