springboot异常统一处理_Spring Boot 统一异常这样处理和剖析,安否?

这篇文章将说明如何统一处理异常,以及其背后的实现原理 ,老套路,先实现,后说明原理,有了上一篇文章的铺底,相信,理解这篇文章就驾轻就熟了

47526bfc9e31b3efde8c37d37864c8c2.png

实现

新建业务异常

新建 BusinessException.class 类表示业务异常, 注意这是一个 Runtime 异常

@Data@AllArgsConstructorpublic final class BusinessException extends RuntimeException { private String errorCode; private String errorMsg; }

添加统一异常处理静态方法

在 CommonResult 类中添加静态方法 errorResult 用于接收异常码和异常消息:

public static  CommonResult errorResult(String errorCode, String errorMsg){ CommonResult commonResult = new CommonResult<>(); commonResult.errorCode = errorCode; commonResult.errorMsg = errorMsg; commonResult.status = -1; return commonResult;}

配置

同样要用到 @RestControllerAdvice 注解,将统一异常添加到配置中:

@RestControllerAdvice("com.example.unifiedreturn.api")static class UnifiedExceptionHandler{ @ExceptionHandler(BusinessException.class) public CommonResult handleBusinessException(BusinessException be){ return CommonResult.errorResult(be.getErrorCode(), be.getErrorMsg()); }}

三部搞定,到这里无论是 Controller 还是 Service 中,只要抛出 BusinessException, 我们都会返回给前端一个统一数据格式。

f52f05e6dfb7b38e5a1b827fc4f1f12d.png

测试

将 UserController 中的方法进行改造,直接抛出异常:

@GetMapping("/{id}")public UserVo getUserById(@PathVariable Long id){ throw new BusinessException("1001
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值