springBoot全局异常处理


对于前后端分离的项目,在后端发生错误时候最好的方式是将错误的信息以json形式返回。

统一返回结果【接口调用成功】【接口异常】

全局异常类注解:

  • 开启了全局异常的捕获 -> @ControllerAdvice @RestControllerAdvice 后者会将数据自动转换成JSON格式返回,类似Controller和RestController。
  • @ExceptionHandler注解可以定义捕获异常的类型即可对这些捕获的异常进行统一的处理

在这里插入图片描述

1、错误响应信息模板ErrorVM类
/**
 * @author: cxt
 * @time: 2021/1/21
 * <p>
 * 错误响应信息模板
 */
@Data
@NoArgsConstructor
public class ErrorVM {
    private Integer code;
    private String message;
    public ErrorVM(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}
2、定义异常处理类APIException类
/**
 * @author: cxt
 * @time: 2021/1/21
 * <p>
 * 产生错误消息
 */
public class ApiException extends RuntimeException {
    @Getter
    @Setter
    private Integer code;

    @Getter
    @Setter
    private String message;

    public ApiException(ErrorVM e) {
        this.code = e.getCode();
        this.message = e.getMessage();
    }

    /**
     * 系统错误
     */
    public static final ErrorVM VERIFICATION_CODE_FAIL = new ErrorVM(-50001, "获取验证码失败");
    public static final ErrorVM E_LOGIN_EXCEPTION = new ErrorVM(-50002, "账户异常");
    public static final ErrorVM E_REGISTER_CREATE_FAILURE = new ErrorVM(-50003, "账号创建失败");

    /**
     * 提示
     */
    public static final ErrorVM E_LOGIN_UNKNOWN_EMPTY = new ErrorVM(-10001, "验证码不能为空");
    public static final ErrorVM E_LOGIN_UNKNOWN_CODE = new ErrorVM(-10002, "验证码错误");
    public static final ErrorVM E_LOGIN_INCORRECT_CREDENTIAL = new ErrorVM(-10003, "账号或者密码错误");
    public static final ErrorVM E_LOGIN_EXCESSIVE_ATTEMPTS = new ErrorVM(-10004, "错误次数过多");
    public static final ErrorVM E_REGISTER_EXISTENCE_ACCOUNT = new ErrorVM(-10006, "注册账号已存在");

    /**
     * 其他错误
     */
    public static final ErrorVM E_REPEAT_UPDATE = new ErrorVM(-10012, "已存在相同的记录");
}
3、全局异常捕获OverallException类
@Slf4j
@ControllerAdvice
public class OverallException {

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public ApiResult<ApiException> custom(HttpServletRequest req, ApiException e) {
        log.error("发生错误!原因是:{}", e.getMessage());
        return ApiResult.error(e.getCode(), e.getMessage());
    }
}
4、定义返回的数据格式ApiResult类
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "统一响应消息")
public class ApiResult<T> implements Serializable {

    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty(value = "状态码", required = true)
    private Integer code;

    @ApiModelProperty(value = "消息", required = true)
    private String message;

    @ApiModelProperty(value = "返回数据")
    private T data;

    public ApiResult(Boolean success, Integer code, String message) {
        this.success = success;
        this.code = code;
        this.message = message;
    }

    public ApiResult(Integer code, String message) {
        this.success = false;
        this.code = code;
        this.message = message;
    }

    /**
     * 成功
     */
    public static <T> ApiResult<T> success() {
        return new ApiResult<>(true, 200, "成功");
    }

    /**
     * 成功:自定义code,消息
     */
    public static <T> ApiResult<T> success(int code, String message) {
        return new ApiResult<>(true, code, message);
    }

    /**
     * 成功:自定义消息
     */
    public static <T> ApiResult<T> success(String message) {
        return new ApiResult<>(true, 200, message);
    }

    /**
     * 成功:返回数据
     */
    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(true, 200, "成功", data);
    }

    /**
     * 成功:自定义消息、返回数据
     */
    public static <T> ApiResult<T> success(String message, T data) {
        return new ApiResult<>(true, 200, message, data);
    }

    /**
     * 成功:自定义消息、返回数据
     */
    public static <T> ApiResult<T> success(int code, String message, T data) {
        return new ApiResult<>(true, code, message, data);
    }

    /**
     * 错误
     */
    public static <T> ApiResult<T> error() {
        return new ApiResult<T>(false, 500, "");
    }

    /**
     * 错误:自定义消息
     */
    public static <T> ApiResult<T> error(ApiException e) {
        return new ApiResult<T>(false, 500, e.getMessage());
    }

    /**
     * 错误:自定义code和消息
     */
    public static <T> ApiResult<T> error(Integer code, String message) {
        return new ApiResult<T>(false, code, message);
    }
}
5、普通类的使用
   /**
     * 验证码验证
     */
    public void verification(String newCode, HttpServletRequest request) {
        if (newCode.isEmpty()) {
            throw new ApiException(ApiException.E_LOGIN_UNKNOWN_EMPTY);
        }
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        String c = code.toLowerCase();
        String v = newCode.toLowerCase();
        if (!v.equals(c)) {
            throw new ApiException(ApiException.E_LOGIN_UNKNOWN_CODE);
        }
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值