当前位置: 首页 > news >正文

Spring Boot 3 全局异常处理终极指南(附完整代码架构),拿走即用

一、为什么需要全局异常处理?

在传统的Spring Boot项目中,每个Controller都需要写大量的try-catch来处理异常,代码重复、可维护性差。全局异常处理通过@ControllerAdvice+@ExceptionHandler统一拦截所有异常,将业务逻辑与异常处理解耦。

本文将带你从零搭建一套完整的全局异常处理架构,包含统一响应体、自定义业务异常、参数校验异常处理、生产级日志链路等,直接复制可用。

二、统一响应体定义

先定义一个标准的API返回格式,让前端统一解析:

@Data @NoArgsConstructor @AllArgsConstructor public class ApiResult<T> { private int code; private String message; private T data; public static <T> ApiResult<T> success(T data) { return new ApiResult<>(200, "success", data); } public static <T> ApiResult<T> error(int code, String message) { return new ApiResult<>(code, message, null); } }

三、自定义业务异常

定义业务异常类,区分系统异常和业务逻辑异常:

@Getter public class BusinessException extends RuntimeException { private final int code; private final String message; public BusinessException(int code, String message) { super(message); this.code = code; this.message = message; } public BusinessException(ErrorCode errorCode) { this(errorCode.getCode(), errorCode.getMessage()); } }

四、全局异常处理器

核心类,统一处理所有异常类型:

@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { // 业务异常 @ExceptionHandler(BusinessException.class) public ApiResult<?> handleBusiness(BusinessException e) { log.warn("业务异常: code={}, msg={}", e.getCode(), e.getMessage()); return ApiResult.error(e.getCode(), e.getMessage()); } // 参数校验异常 @ExceptionHandler(MethodArgumentNotValidException.class) public ApiResult<?> handleValidation(MethodArgumentNotValidException e) { String msg = e.getBindingResult().getFieldErrors().stream() .map(err -> err.getField() + ": " + err.getDefaultMessage()) .collect(Collectors.joining(", ")); return ApiResult.error(400, msg); } // 参数类型不匹配 @ExceptionHandler(ConstraintViolationException.class) public ApiResult<?> handleConstraint(ConstraintViolationException e) { return ApiResult.error(400, e.getMessage()); } // 404 @ExceptionHandler(NoHandlerFoundException.class) public ApiResult<?> handleNotFound(NoHandlerFoundException e) { return ApiResult.error(404, "接口不存在"); } // 顶级异常兜底 @ExceptionHandler(Exception.class) public ApiResult<?> handleException(Exception e) { log.error("系统异常: ", e); return ApiResult.error(500, "服务器繁忙,请稍后重试"); } }

五、错误码枚举

@Getter @AllArgsConstructor public enum ErrorCode { // 通用 PARAM_ERROR(400, "参数错误"), UNAUTHORIZED(401, "未登录"), FORBIDDEN(403, "无权限"), NOT_FOUND(404, "资源不存在"), SYSTEM_ERROR(500, "系统异常"), // 业务 USER_NOT_EXIST(1001, "用户不存在"), USER_PASSWORD_ERROR(1002, "密码错误"), ORDER_NOT_FOUND(2001, "订单不存在"), ORDER_STATUS_ERROR(2002, "订单状态异常"); private final int code; private final String message; }

六、在Controller中使用

@RestController @RequestMapping("/user") public class UserController { @GetMapping("/{id}") public ApiResult<User> getUser(@PathVariable Long id) { if (id == null || id <= 0) { throw new BusinessException(ErrorCode.PARAM_ERROR); } User user = userService.findById(id); if (user == null) { throw new BusinessException(ErrorCode.USER_NOT_EXIST); } return ApiResult.success(user); } @PostMapping public ApiResult<Void> createUser(@Valid @RequestBody UserCreateRequest request) { userService.create(request); return ApiResult.success(null); } }

七、生产环境建议

  1. 日志链路:在全局异常中加入traceId,配合MDC实现全链路追踪
  2. 告警通知:针对500系统异常,接入钉钉/企微机器人告警
  3. 敏感信息过滤:生产环境不返回堆栈信息,只返回code+message
  4. 国际化支持:通过Accept-Language返回对应语言的错误信息
  5. 单元测试:为每个异常处理逻辑编写测试用例,确保覆盖率

这套架构我已经在多个生产项目中验证过,从单体应用到微服务都能直接套用。如果你有更好的实践,欢迎在评论区分享交流。

http://www.jsqmd.com/news/820728/

相关文章:

  • 如何摆脱游戏卡顿困扰:DLSS Swapper的智能性能管理方案
  • 为什么FreeBSD和苹果都爱用Clang?聊聊它的模块化设计与商业友好性
  • 优雅进程终止:Go工具halt的设计原理与实战应用
  • 泉州 CPPM 认证培训 福建制造业采购必考证书 - 中供国培
  • 全屋定制酒柜技术拆解:从板材到工艺的硬核标准 - 奔跑123
  • Linux 端口管理指南
  • 当用户觉得 Agent 变笨时,真正退化的往往不是模型
  • 大模型小白入门指南:3分钟读懂核心逻辑+高性价比产品推荐(建议收藏+转发)
  • 2026年OpenAI API聚合站权威推荐:为开发者与企业提供全方位的可靠选型指南
  • 人工智能生成内容的文化影响:第一部分
  • 【权威实测】Perplexity UI v2.8.3组件查询API响应延迟骤降76%的6项必调参数
  • Rust 实现轻量级终端复用器 Kibitz:零配置的会话管理利器
  • 2026 年 5 月常州劳力士欧米茄浪琴市场行情对比 - 奢侈品回收测评
  • 2026 济南黄金回收高价变现攻略|拿捏出手时机,多赚不少钱 - 奢侈品回收测评
  • C# —— 上位机行业解析与完整学习规划
  • 别盲目跟风!程序员转智能体开发,先看这篇避坑指南
  • 收藏!小白程序员必看:AI抢工作?2026年高薪新职业已出现!速进!
  • 最近,程序员的离职潮彻底消失了。。。
  • ResearcherSkill项目:构建高效可复现的科研工作流与知识管理体系
  • 基于Astro与TypeScript构建实时星图:技术架构与天文数据可视化实践
  • 全屋定制技术拆解:从板材到售后的硬核选型逻辑 - 奔跑123
  • 嘉兴 CPPM 报考流程 在职采购业余取证方案(浙江官方授权中心) - 中供国培
  • 国内专业刺绣章定制企业排行:实力厂商综合一览 - 奔跑123
  • 本地化AI编程副驾驶jaipilot-cli:终端集成与高效开发实践
  • 3步解锁小爱音箱隐藏技能:用xiaomusic打造专属智能音乐中心
  • CatchClaw爬虫框架:从零构建高效异步网络爬虫的实践指南
  • 矩阵融合,跨镜永续追踪三维重构,跨镜轨迹锁定
  • 江西德兴市发布严打烟花违法通告(地方政策)
  • 2026年在线脑图工具深度横评:7款主流平台技术向实测与选型建议
  • 郑州闲置黄金变现|免费估价、六环内上门,足金金条全品类收 - 奢侈品回收测评