Spring boot -> 为什么我不需要在服务中捕获异常?



我用spring boot构建了一个rest api,我不明白为什么我不必在方法中捕获自己的异常。。

请查看代码中的FIRST_IMPORTANT_LINE,此函数(isemptyfile(在SECOND_IMPORTNT_LINE处抛出EmptyFileException。

事实证明,intellij并没有让我在THIRD_IMPORTANT_LINE中捕捉到这个异常。出于某种原因,我的例外只是去了其他地方,即,当我使用junit调试ImageService的测试时,在达到SECOND_IMPORTANT_LINE后,异常直接进入测试方法

有人能向我解释这种行为吗?如何正确处理此异常?

谢谢!

这是代码->


@Service
public class ImageService {
private final FileStore fileStore;
private final UserService userService;
@Autowired
public ImageService(FileStore fileStore, UserService userService) {
this.fileStore = fileStore;
this.userService = userService;
}
public void uploadImageToS3(int userProfileId, MultipartFile file){
try{
isFileEmpty(file);  //***********FIRST_IMPORTANT_LINE***********
isImage(file);
User user = userService.getUser(userProfileId);
Map<String,String> metadata = extractMetaData(file);
String path = MessageFormat.format("{0}/{1}", BucketName.PROFILE_IMAGE.getBucketName(),user.getId());
String[] filenameArray = file.getOriginalFilename().split("\.");
String fileNameWithoutExtension = filenameArray[0];
String extension = filenameArray[1];
String fileName = MessageFormat.format("{0}-{1}.{2}",fileNameWithoutExtension,UUID.randomUUID(),extension);

fileStore.save(path,fileName,Optional.of(metadata),file.getInputStream());
//update user link -- filename
}
catch (IOException|UserNotFoundException e){
///***********THIRD_IMPORTANT_LINE***********
throw new IllegalStateException(e);
}
}
private void isFileEmpty(MultipartFile file){
if(file == null || file.isEmpty()){
throw new EmptyFileException("cannot upload empty file"); //***********SECOND_IMPORTANT_LINE***********
}
}
}

IllegalStateException继承自RuntimeException,这是一个未检查的异常。请参阅JavaDocs,特别是这一行:

RuntimeException及其子类是未检查的异常。如果未选中的异常可以由方法或构造函数的执行引发并在方法或构造函数边界之外传播,则无需在方法或构造器的throws子句中声明。

相关内容

最新更新