异常处理返回结构体,做到全局统一

结合上篇博客:自研究一套返回结构体 上篇博客讲解的是正常返回结构体情况,这篇博客针对的是异常情况下返回结构体的处理。

针对异常有自定义异常,运行时异常和检查性异常。

自定义异常(也叫业务异常)

自定义异常作用:方便开发者使用,针对那些请求必要参数及数据库返回数据的处理。

代码实践:需自定义一个异常类,然后才可被使用

存在成员属性ErrorCode类型的errorCode,并定义两个构造函数,第一个是无参构造并为errorCode赋予一个默认值,第二个是ErrorCode的有参构造,直接为它赋值且可进行占位处理。

@Getter
public final class ServiceException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    private ErrorCode errorCode;

    /**
     * 空构造方法,避免无参初始化错误
     */
    public ServiceException() {
        this.errorCode = ErrorCode.FAIL;
    }

    public ServiceException(ErrorCode errorCode, Object... ds) {
        super(errorCode.getMsg(ds));
        //使用临时对象是避免占位符无法使用
        ErrorCode temCode = ErrorCode.ERROR_CODE_TEMP;
        temCode.setCode(errorCode.getCode()).setMessage(String.format(errorCode.getMessage(), ds))
                .setEnMessage(String.format(errorCode.getEnMessage(), ds));
        this.errorCode = temCode;
    }

}
如何使用
  1. 下面例子是用户登录情况下,从数据库查询出用户数据并进行校验处理,如果符合要求可往后进行下去,不符合直接抛出ServiceException。
       if (StringUtils.isNull(user)) {
            log.info("登录用户:{} 不存在.", username);
            throw new ServiceException(ErrorCode.WEB_USER_LOGIN_NOT_EXIST, username);
        } else if (BaseConstant.USER_DELETED_STATUS.equals(user.getDelFlag())) {
            log.info("登录用户:{} 已被删除.", username);
            throw new ServiceException(ErrorCode.WEB_USER_LOGIN_HAS_DELETED, username);
        } else if (BaseConstant.USER_DISABLE_STATUS.equals(user.getStatus())) {
            log.info("登录用户:{} 已被停用.", username);
            throw new ServiceException(ErrorCode.WEB_USER_LOGIN_HAS_DEACTIVATED, username);
        }

上述例子写起代码比较麻烦,而且他们的结构都差不多,要写三行且符合要求就向外抛出,那么有没有一种简单方法进行处理呢?

  1. 简单实践:

需先定义一个断言类,然后直接调用即可

public class Assert {

    public static void isTrue(boolean condition, ErrorCode errorCode, Object... ds) {
        if (condition) {
            throw new ServiceException(errorCode, ds);
        }
    }

    public static void isFalse(boolean conditon, ErrorCode errorCode, Object... ds) {
        isTrue(!conditon, errorCode, ds);
    }

    public static void isNull(Object obj, ErrorCode errorCode, Object... ds) {
        if (StringUtils.isNull(obj)) {
            throw new ServiceException(errorCode, ds);
        }
    }

    public static void notNull(Object obj, ErrorCode errorCode, Object... ds) {
        if (StringUtils.isNotNull(obj)) {
            throw new ServiceException(errorCode, ds);
        }
    }

    public static void isEmpty(String str, ErrorCode errorCode, Object... ds) {
        if (StringUtils.isEmpty(str)) {
            throw new ServiceException(errorCode, ds);
        }
    }

    public static void isNotEmpty(String str, ErrorCode errorCode, Object... ds) {
        if (StringUtils.isNotEmpty(str)) {
            throw new ServiceException(errorCode, ds);
        }
    }
}

进行使用:上述代码例子可简单变成下面代码

Assert.isNull(user,ErrorCode.WEB_USER_LOGIN_NOT_EXIST, username);

Assert.isTrue(BaseConstant.USER_DELETED_STATUS.equals(user.getDelFlag()),ErrorCode.WEB_USER_LOGIN_HAS_DELETED, username);

Assert.isTrue(BaseConstant.USER_DISABLE_STATUS.equals(user.getStatus()),ErrorCode.WEB_USER_LOGIN_HAS_DEACTIVATED, username);

上述是自定义异常的使用,还需要全局异常处理才能将异常返回结构统一。

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResultBody handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return ResultBodyUtils.fail(e.getErrorCode());
    }
运行时异常和检查性异常

针对运行时异常和检查性异常抛出也可全局异常处理使返回结构体统一。

 /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultBody handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResultBodyUtils.fail(ErrorCode.SYSTEM_ERROR_500, requestURI);
    }

综合:那么这样就可以做到使用这一套返回结构体能够将返回结构统一,而且使用起来非常方便。

相关推荐

  1. 异常处理返回结构做到全局统一

    2023-12-15 11:44:04       45 阅读
  2. SpringBoot 统一后端返回格式、处理全局异常

    2023-12-15 11:44:04       19 阅读
  3. 75.实现统一异常处理和封装统一返回结果

    2023-12-15 11:44:04       35 阅读
  4. SpringBoot实现自定义异常+全局异常统一处理

    2023-12-15 11:44:04       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-15 11:44:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-15 11:44:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-15 11:44:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-15 11:44:04       20 阅读

热门阅读

  1. electron这样使用更安全

    2023-12-15 11:44:04       78 阅读
  2. Qt插件开发与QPluginLoader的使用

    2023-12-15 11:44:04       36 阅读
  3. 安卓10 flutter webview 回退会闪退

    2023-12-15 11:44:04       47 阅读
  4. 数据结构:第9关:删除链表中满足区间值的结点

    2023-12-15 11:44:04       44 阅读