Spring Boot 全局异常处理
2025/11/30大约 2 分钟
全局异常处理
全局异常捕获
- 首先定义全局异常处理器
/**
* 全局异常处理器,处理项目中抛出的业务异常
*/
@Slf4j
@RestControllerAdvice // 统一异常拦截(返回 JSON)
public class GlobalExceptionHandler {
/**
* 专门处理我们自定义的业务异常
*/
@ExceptionHandler(BaseException.class)
public Result<Void> handleBaseException(BaseException ex) {
log.warn("业务异常: {}", ex.getMessage());
// code 允许为 null,因此要判断
if (ex.getCode() != null) {
return Result.error(ex.getCode(), ex.getMessage());
}
// 如果没有 code,默认 500
return Result.error(ex.getMessage());
}
/**
* 处理所有未捕获的异常(兜底)
*/
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception ex) {
log.error("系统异常: ", ex);
return Result.error(500, "系统异常,请联系管理员");
}
}需要使用@RestControllerAdvice注释为全局异常处理器
使用@ExceptionHandler 捕获异常。
- 定义BaseException继承RuntimeException
/**
* 业务异常
*/
/**
* 业务异常
*/
public class BaseException extends RuntimeException {
private Integer code;
public BaseException(String msg) {
super(msg);
}
public BaseException(Integer code,String msg){
super(msg);
this.code = code;
}
public Integer getCode() {
return code;
}
}- 自定义异常
/**
* 密码错误异常
*/
public class PasswordErrorException extends BaseException {
public PasswordErrorException() {
}
public PasswordErrorException(String msg) {
super(msg);
}
}- 实现类中抛出自定义异常
if (!password.equals(employee.getPassword())) {
//密码错误
throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
}🎯 关键执行节点
| 步骤 | 执行位置 | 关键动作 | 结果 |
|---|---|---|---|
| 1 | Service层 | 密码不匹配,抛出异常 | 创建PasswordErrorException实例 |
| 2 | Service层 | 方法立即终止 | 后续代码不会执行 |
| 3 | Controller层 | 异常向上传播 | 方法提前结束 |
| 4 | 全局异常处理器 | 匹配异常类型 | 找到@ExceptionHandler(BaseException.class) |
| 5 | 全局异常处理器 | 记录错误日志 | 输出到日志文件 |
| 6 | 全局异常处理器 | 封装统一响应 | 返回Result对象 |
| 7 | 客户端 | 接收错误响应 | 显示错误信息 |
