Spring Boot -> 为什么我不需要在服务内部捕获我的异常?

huangapple go评论75阅读模式
英文:

Spring boot -> why i dont need to catch my exceptions inside a service?

问题

@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***********
        }
    }
}
英文:

im bulding a rest api with spring boot and i cant figure out why i dont have to catch my own exceptions inside a method..

please take a look at the FIRST_IMPORTANT_LINE at the code, this function (isemptyfile) throws an EmptyFileException at SECOND_IMPORTANT_LINE.

it turns out that intellij doesnt make me to catch this exception in THIRD_IMPORTANT_LINE.
for some reason my exception just get to somewhere else,
i.e. when i debug the test of ImageService with junit the exception goes right to the test method after reaching SECOND_IMPORTANT_LINE

someone can explain to me this behavior? and how can i handle this exception properly?

thanks!

here is the code ->


@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&lt;String,String&gt; metadata = extractMetaData(file);
String path = MessageFormat.format(&quot;{0}/{1}&quot;, BucketName.PROFILE_IMAGE.getBucketName(),user.getId());
String[] filenameArray = file.getOriginalFilename().split(&quot;\\.&quot;);
String fileNameWithoutExtension = filenameArray[0];
String extension = filenameArray[1];
String fileName = MessageFormat.format(&quot;{0}-{1}.{2}&quot;,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(&quot;cannot upload empty file&quot;); //***********SECOND_IMPORTANT_LINE***********
}
}
}

答案1

得分: 1

IllegalStateException继承自RuntimeException,后者是一种未经检查的异常。请参阅JavaDocs中的相关内容,特别是这一行:

> RuntimeException及其子类是未经检查的异常。如果方法或构造函数的执行可能会抛出这些异常,并在方法或构造函数边界之外传播,那么它们无需在方法或构造函数的throws子句中声明。

英文:

IllegalStateException inherits from RuntimeException, which is an unchecked exception. See JavaDocs for that one, specifically this line:

> RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

huangapple
  • 本文由 发表于 2020年10月11日 22:03:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64304866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定