一、为什么要处理全局异常
如下,当系统出现异常时,返回系统默认的错误信息,不是和前端约定的标准数据格式,给前端统一逻辑处理带来困难
{
"timestamp": "2023-10-09T05:50:47.644+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/userInfo/testException"
}
二、添加业务异常类
package com.example.demo.common.http;
public class BusinessException extends RuntimeException {
public BusinessException(String msg) {
super(msg);
}
}
三、配置全局异常处理类
-
RestCode下添加枚举
BUSINESS_EXCEPTION("999998", "业务异常"), -
RestResult添加默认无参构造函数
public RestResult() {
}
- 添加全局异常处理类
package com.example.demo.common.http;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public RestResult handleBusinessException(BusinessException e) {
e.printStackTrace();
return new RestResult().setCode(RestCode.BUSINESS_EXCEPTION.getCode()).setMsg(e.getMessage());
}
@ExceptionHandler(Exception.class)
public RestResult<String> handleException(Exception e) {
e.printStackTrace();
return new RestResult().setCode(RestCode.FAIL.getCode()).setMsg(e.getMessage());
}
}
对业务异常统一拦截,返回错误码为"999998",对于其他异常,返回错误码为"999999"
四、功能验证
package com.example.demo.controller;
import com.example.demo.common.http.BusinessException;
import com.example.demo.common.http.RestResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("userInfo")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@PostMapping("/selectById")
public RestResult<UserInfo> selectById(Long id) {
UserInfo userInfo = userInfoService.selectById(id);
if (null == userInfo) {
throw new BusinessException("用户不存在");
}
return RestResult.getSuccessResult(userInfo);
}
@PostMapping("/testException")
public RestResult<UserInfo> testException(Long id) {
UserInfo userInfo = null;
userInfo.getId();
return RestResult.getSuccessResult();
}
}
访问http://localhost:8080/userInfo/selectById?id=3返回
{
"code": "999998",
"msg": "用户不存在",
"data": null
}
访问http://localhost:8080/userInfo/testException?id=3返回
{
"code": "999999",
"msg": null,
"data": null
}
五、项目地址
PS:可以通过tag下载本文对应的代码版本
六、结尾
全局异常处理已完成,有问题可以联系chenzhenlindx@qq.com