这篇文章将说明如何统一处理异常,以及其背后的实现原理 ,老套路,先实现,后说明原理,有了上一篇文章的铺底,相信,理解这篇文章就驾轻就熟了
![47526bfc9e31b3efde8c37d37864c8c2.png](https://i-blog.csdnimg.cn/blog_migrate/2fbe5b9a508e47ef242ee94ef388a1b0.jpeg)
实现
新建业务异常
新建 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](https://i-blog.csdnimg.cn/blog_migrate/9d9f3e49fb23657ad1f5eed214bdbf7b.jpeg)
测试
将 UserController 中的方法进行改造,直接抛出异常:
@GetMapping("/{id}")public UserVo getUserById(@PathVariable Long id){ throw new BusinessException("1001