Springboot 全局异常捕获以及统一接口返回结果

本文介绍了如何在SpringBoot中实现全局异常捕获和统一接口返回结果。通过创建一个`BizException`类继承`RuntimeException`,并定义一个`GlobalExceptionHandler`控制器建议类来处理各种异常情况,如`NullPointerException`、`HttpRequestMethodNotSupportedException`和未处理的异常。此外,还展示了如何在`UserController`中模拟异常并返回统一的错误码。
摘要由CSDN通过智能技术生成

public String toString() {

return JSONObject.toJSONString(this);

}

}

OK,到此关于返回码的东西以及大致完毕,我们现在开始写关于异常捕捉的。

首先写一个异常类继承RuntimeException,  BizException.java:

/**

  • @Author:JCccc

  • @Description:

  • @Date: created in 15:18 2019/5/3

*/

public class BizException extends RuntimeException {

private static final long serialVersionUID = 1L;

/**

  • 错误码

*/

protected String errorCode;

/**

  • 错误信息

*/

protected String errorMsg;

public BizException() {

super();

}

public BizException(BaseErrorInfoInterface errorInfoInterface) {

super(errorInfoInterface.getResultCode());

this.errorCode = errorInfoInterface.getResultCode();

this.errorMsg = errorInfoInterface.getResultMsg();

}

public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {

super(errorInfoInterface.getResultCode(), cause);

this.errorCode = errorInfoInterface.getResultCode();

this.errorMsg = errorInfoInterface.getResultMsg();

}

public BizException(String errorMsg) {

super(errorMsg);

this.errorMsg = errorMsg;

}

public BizException(String errorCode, String errorMsg) {

super(errorCode);

this.errorCode = errorCode;

this.errorMsg = errorMsg;

}

public BizException(String errorCode, String errorMsg, Throwable cause) {

super(errorCode, cause);</

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值