自定义业务异常


在开发项目的工程中,经常需要定义属于自己系统的业务异常,所以这里做一个记录分享。

一、继承RuntimeException

maven依赖:

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.0</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

/**
 * 业务异常
 * @author fck
 */
public class BusinessException extends RuntimeException{

    private Integer code;
    private String message;
    public BusinessException() {
    }

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

    public Integer getCode() {
        return code;
    }

    public static BusinessException build(Integer code, String message){
        return new BusinessException(code,message);
    }

    @Override
    public synchronized Throwable fillInStackTrace() {
        return this;
    }
}

二、自定义异常常量

/**
 * 异常常量
 * @author fck
 */
public interface ExceptionConst {

    /**
     * 当前系统的异常码10001 - 100000
     */
    interface CurrentSystem{
        BusinessException SYSTEM_ERROR = BusinessException.build(10001,"系统异常,请联系管理员");
        BusinessException VALIDATE_ERROR = BusinessException.build(10002,"入参校验异常");
    }
    /**
     * 客户信息异常码 100001 - 100090
     * @author wangxw
     */
    interface EnpterPriseException{
        BusinessException ENTP_EMPTY_EXCEPTION = BusinessException.build(100001,"未获取到用户信息");
        BusinessException ENTP_ALLOW_FILE_MAX_EXCEPTION = BusinessException.build(100002,"用户信息最大不得超过20M");
        BusinessException ENTP_INIT_USER_INFO_EMPTY_EXCEPTION = BusinessException.build(100003,"初始化用户信息失败");
        BusinessException ENTP_REG_USER_EXIST_EXCEPTION = BusinessException.build(100004,"注册用户已存在用户表中");

    }

}

测试

这里就简单做个测试示例:

/**
 * @author fck
 * @version 1.0
 * @date 2021/11/2 15:03
 */
@Api("自定义业务异常测试")
@RestController
public class BusinessExceptionController {

    @GetMapping("/test")
    public String getName(String name){
        if (StringUtils.isEmpty(name)){
            throw ExceptionConst.CurrentSystem.SYSTEM_ERROR;
        }
        return name;
    }
}

在这里插入图片描述

在这里插入图片描述

总结

根据不同的业务系统,可以定义不同的系统常量,来满足需求所需,各位小伙伴可各取所需。


版权声明:本文为qq_49281137原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。