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

Spring的异常处理机制详解

在Spring Boot MVC架构中,如果Service方法中的异常没有被捕获也没有被抛出,异常的处理流程如下:

1.默认异常处理流程

@RestControllerpublicclassUserController{@AutowiredprivateUserServiceuserService;@GetMapping("/user/{id}")publicUsergetUser(@PathVariableLongid){// 如果Service抛出异常且没有被捕获returnuserService.findById(id);// 异常会向上传播}}@ServicepublicclassUserService{publicUserfindById(Longid){// 这里发生异常(比如NullPointerException)// 但没有try-catch,也没有声明throwsreturnuserRepository.findById(id).orElseThrow(()->newRuntimeException("User not found"));}}

2.异常的传播路径

Service层异常 → Controller层 → DispatcherServlet → 框架处理

具体处理方式:

3.运行时异常(RuntimeException)

@ServicepublicclassUserService{publicvoidprocess(){// 运行时异常会自动向上传播intresult=10/0;// ArithmeticException}}

处理结果

  • 异常会传播到Controller
  • 如果没有@ExceptionHandler处理,会到DispatcherServlet
  • 最终返回HTTP 500状态码

4.受检异常(Checked Exception)

@ServicepublicclassUserService{publicvoidreadFile(){// 编译错误:必须处理或声明抛出// FileReader fr = new FileReader("file.txt");}publicvoidreadFile2()throwsIOException{// 必须声明throwsFileReaderfr=newFileReader("file.txt");}}

关键区别

  • 受检异常:编译时会报错,必须处理
  • 运行时异常:编译通过,运行时才暴露

5.Spring的异常处理机制

A. Controller级别的@ExceptionHandler

@RestControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(RuntimeException.class)publicResponseEntity<String>handleRuntimeException(RuntimeExceptione){returnResponseEntity.status(500).body("Service Error: "+e.getMessage());}}

B. Service层使用声明式事务

@Service@TransactionalpublicclassUserService{publicvoidupdateUser(Useruser){// 事务方法中的异常会导致事务回滚userRepository.save(user);thrownewRuntimeException("Test rollback");}}

6.实际影响和最佳实践

不推荐的做法

@ServicepublicclassUserService{publicvoidriskyMethod(){// 异常被"吞掉",调用方不知道出错try{// 可能抛出异常的操作}catch(Exceptione){// 空的catch块,不记录也不抛出}}}

推荐的最佳实践

方案1:统一异常处理
@ServicepublicclassUserService{publicUserfindById(Longid){returnuserRepository.findById(id).orElseThrow(()->newUserNotFoundException("User not found with id: "+id));}}// 自定义业务异常publicclassUserNotFoundExceptionextendsRuntimeException{publicUserNotFoundException(Stringmessage){super(message);}}
方案2:使用AOP统一处理
@Aspect@ComponentpublicclassServiceExceptionAspect{@AfterThrowing(pointcut="execution(* com.example.service.*.*(..))",throwing="ex")publicvoidhandleServiceException(Exceptionex){// 记录日志、监控等log.error("Service层异常: ",ex);}}
方案3:响应式异常处理
@ServicepublicclassUserService{@TransactionalpublicUsercreateUser(UserDTOdto){try{// 业务逻辑returnuserRepository.save(user);}catch(DataIntegrityViolationExceptione){thrownewBusinessException("用户已存在",e);}catch(Exceptione){log.error("创建用户失败",e);thrownewSystemException("系统错误,请稍后重试",e);}}}

7.重要结论

  1. 运行时异常:会自动传播,最终返回HTTP 500
  2. 受检异常:编译时强制要求处理
  3. 默认响应:未处理的异常会生成包含错误详情的HTTP 500响应
  4. 事务影响:Spring事务管理会回滚运行时异常
  5. 日志记录:异常栈会记录在服务器日志中

建议:即使在Service层,也应该适当处理异常,至少记录日志,并根据业务需要转换为合适的业务异常再向上抛出。

http://www.zskr.cn/news/159795.html

相关文章:

  • LLM 实战:Teacher-Student 知识蒸馏
  • 2025年技术人才外派公司全攻略:核心误区、能力对比与落地避坑指南
  • Java 异常捕获基础知识:Exception、Error 和 Throwable
  • 锐捷设备批量下发配置telnetlib模块
  • 【谁懂啊!科研狗的降重血泪史谁能破?】
  • 华为批量下发配置命令使用telnetlib模块
  • shift-register应用案例
  • 乐享云 v1.1.0| 不限速磁力下载,边下边播,内置字幕匹配
  • 重庆理工大学(CQUT)物理实验一RLC串联谐振
  • 东方博宜OJ 2557:幂次求和 ← 数位DP
  • 论文 “去红去机” 兵器谱:这9款工具,重复率 + AIGC 疑似度双降
  • Java毕设项目:基于微服务教材征订系统(源码+文档,讲解、调试运行,定制等)
  • 线下挑儿童羽绒服不踩坑!2025年口碑品牌实测指南(宝妈必收) - 品牌测评鉴赏家
  • 英语_阅读_tanker trucks for carrying edible oil_待读
  • 深入解析:GitHub 一周热门项目速览 | 2025年12月1日
  • 为GIT仓库项目设置独立配置参数
  • scrapy基础知识之发送POST请求
  • 如何开启第一次开源贡献之路?
  • Python返回数组/List长度的方法
  • 论文AI率卡在20%?试试这十佳降AI软件,专治各种检测不过
  • 微店商品详情API使用指南
  • 2025年儿童鞋服品牌前十名盘点:专业、舒适、潮流怎么选? - 品牌测评鉴赏家
  • 国货之光!这10+国产儿童鞋服品牌闭眼入,宝妈收藏这篇就够了 - 品牌测评鉴赏家
  • DBeaver设置不断开连接
  • 1.磁盘阵列
  • 【社交APP上线记】小夏、老周、小林的讨论组
  • 宝妈宝爸闭眼入!0 - 16岁儿童鞋服优质品牌大盘点 - 品牌测评鉴赏家
  • 城市仿真软件:CityEngine_(18).性能优化与渲染技术
  • CSS3 字体
  • 通信协议仿真:5G NR协议仿真_(13).5G NR仿真中的资源管理