益阳市网站建设_网站建设公司_CSS_seo优化
2025/12/26 23:13:28 网站建设 项目流程

在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层,也应该适当处理异常,至少记录日志,并根据业务需要转换为合适的业务异常再向上抛出。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询