PotPlayer字幕翻译插件完整教程:3步实现多语言实时翻译
2025/12/27 1:27:30
在Spring Boot MVC架构中,如果Service方法中的异常没有被捕获也没有被抛出,异常的处理流程如下:
@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"));}}Service层异常 → Controller层 → DispatcherServlet → 框架处理@ServicepublicclassUserService{publicvoidprocess(){// 运行时异常会自动向上传播intresult=10/0;// ArithmeticException}}处理结果:
@ServicepublicclassUserService{publicvoidreadFile(){// 编译错误:必须处理或声明抛出// FileReader fr = new FileReader("file.txt");}publicvoidreadFile2()throwsIOException{// 必须声明throwsFileReaderfr=newFileReader("file.txt");}}关键区别:
@RestControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(RuntimeException.class)publicResponseEntity<String>handleRuntimeException(RuntimeExceptione){returnResponseEntity.status(500).body("Service Error: "+e.getMessage());}}@Service@TransactionalpublicclassUserService{publicvoidupdateUser(Useruser){// 事务方法中的异常会导致事务回滚userRepository.save(user);thrownewRuntimeException("Test rollback");}}@ServicepublicclassUserService{publicvoidriskyMethod(){// 异常被"吞掉",调用方不知道出错try{// 可能抛出异常的操作}catch(Exceptione){// 空的catch块,不记录也不抛出}}}@ServicepublicclassUserService{publicUserfindById(Longid){returnuserRepository.findById(id).orElseThrow(()->newUserNotFoundException("User not found with id: "+id));}}// 自定义业务异常publicclassUserNotFoundExceptionextendsRuntimeException{publicUserNotFoundException(Stringmessage){super(message);}}@Aspect@ComponentpublicclassServiceExceptionAspect{@AfterThrowing(pointcut="execution(* com.example.service.*.*(..))",throwing="ex")publicvoidhandleServiceException(Exceptionex){// 记录日志、监控等log.error("Service层异常: ",ex);}}@ServicepublicclassUserService{@TransactionalpublicUsercreateUser(UserDTOdto){try{// 业务逻辑returnuserRepository.save(user);}catch(DataIntegrityViolationExceptione){thrownewBusinessException("用户已存在",e);}catch(Exceptione){log.error("创建用户失败",e);thrownewSystemException("系统错误,请稍后重试",e);}}}建议:即使在Service层,也应该适当处理异常,至少记录日志,并根据业务需要转换为合适的业务异常再向上抛出。