英文:
In Spring Data, should I be paranoid about handling all possible exceptions?
问题
假设我有这行代码:
@Override
public Optional<Category> getCategoryById(int id) {
return repository.findById(id);
}
Spring Data的文档对于 "findById" 函数有如下说明:
Throws:
IllegalArgumentException – 如果 id 为 null。
在我的情况下,它绝对不会是 null,所以我是否仍然应该添加 try catch 块来处理如果发生错误呢?
另外,我应该尝试捕获它并进行相应处理吗?还是应该让它被抛出,然后让 @ControllerAdvice/Exception Handler 处理并向用户返回错误呢?
英文:
Suppose I have this line of code
@Override
public Optional<Category> getCategoryById(int id) {
return repository.findById(id);
}
The documentation of spring data says about the "findById" function:
Throws:
IllegalArgumentException – if id is null.
In my case, there is NO WAY it can ever be null, so should I still add try catch block to handle if an error ever occurs?
Also, should try/catch it and handle accordingly? OR should I let it be thrown and let
@ControllerAdvice/Exception Handler handle it and return back to the user the error?
答案1
得分: 0
通常情况下,如果您可以确保该方法永远不会传递一个不存在的 ID,您可以考虑使用来自 Lombok 项目的@SneakyThrows注解。
假设这是一个较大的项目,请确保您对@SneakyThrows的使用进行了文档化。
英文:
Generally, if you can guarantee that this method will never be passed a non-existing ID you could consider @SneakyThrows
from project Lombok.
Assuming this is a larger Project make sure your use of @SneakyThrows is documented.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论