在Spring Data中,我应该对处理所有可能的异常保持警惕吗?

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

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&lt;Category&gt; 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.

huangapple
  • 本文由 发表于 2020年9月1日 02:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63675889.html
匿名

发表评论

匿名网友

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

确定