第16节:全局统一异常优化 + 自定义业务异常
前面我们有全局异常处理器,现在升级它:抽出自定义业务异常,区分业务报错和系统报错,返回更规范的信息,方便前端处理。
1. 新建自定义业务异常 com.zzs.szyt.exception.BizException
package com.zzs.szyt.exception;
import lombok.Data;
/**
* 自定义业务异常:业务上预期的错误,例如 用户不存在、参数非法
*/
@Data
public class BizException extends RuntimeException {
private Integer code;
private String msg;
public BizException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public BizException(String msg) {
// 默认业务异常码,和Result里统一
this(500, msg);
}
}
2. 改造统一返回 Result,配套业务码
package com.zzs.szyt.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
private Integer code;
private String msg;
private T data;
// 成功
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
public static <T> Result<T> success() {
return new Result<>(200, "操作成功", null);
}
// 业务失败
public static <T> Result<T> fail(String msg) {
return new Result<>(500, msg, null);
}
public static <T> Result<T> fail(Integer code, String msg) {
return new Result<>(code, msg, null);
}
}
3. 修改全局异常处理器 GlobalExceptionHandler
区分:
-
BizException:业务异常 → 返回业务提示,不打 ERROR 堆栈(或者精简日志) -
其他 Exception:未知系统异常 → 打印完整错误栈,提示 "系统异常"
package com.zzs.szyt.common;
import com.zzs.szyt.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/** * 捕获自定义业务异常 */ @ExceptionHandler(BizException.class) public Result<?> handleBizException(BizException e) { log.warn("业务异常:{}", e.getMsg()); return Result.fail(e.getCode(), e.getMsg()); } /** * 捕获所有其他未知异常 */ @ExceptionHandler(Exception.class) public Result<?> handleException(Exception e) { log.error("系统异常:", e); return Result.fail(500, "服务器内部异常,请联系管理员"); }}
4. 在业务代码里使用(示例 UserService)
原来判断用户不存在 return Result.fail,改成抛出业务异常,全局统一接管返回:
@Override
public User getById(Long id) {
User user = super.getById(id);
if (user == null) {
throw new BizException("用户不存在");
}
return user;
}
Controller 就不用写 if(user == null) 判断返回失败了,简洁很多:
@GetMapping("/{id}")
public Result<User> getById(@PathVariable Long id) {
User user = userService.getById(id);
return Result.success(user);
}
5. 测试效果
请求一个不存在 id,返回:
{
"code": 500,
"msg": "用户不存在",
"data": null
}
- 业务异常日志是 warn,不会堆满红色报错栈;
- 空指针、数据库异常这类属于系统异常,打印完整堆栈,给开发排查;
- 所有接口不用重复写异常判断,统一收口。
本节小结
- 区分【业务异常】和【系统异常】,是后端规范写法;
@RestControllerAdvice全局捕获,所有 Controller 统一生效;- 业务抛出
BizException,代码更清爽。
