[英]Spring Boot - throw exception or indicate item is not found
I've written two methods, findById
searches for an item in the DB and throws an exception if the item is not found:我写了两个方法,
findById
在数据库中搜索一个项目,如果找不到该项目则抛出异常:
public Url findById(final Long id){
return urlRepository.findById(id)
.orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}
The second method, findByShortUrl
searches for an item in the DB and uses the JPA
method findByShortUrlIs
which returns a List of size 1 if the item is found, there should never be more than 1 item in the DB for a given shortUrl:第二种方法
findByShortUrl
在数据库中搜索一个项目并使用JPA
方法findByShortUrlIs
如果找到该项目,它返回一个大小为 1 的列表,对于给定的 shortUrl,数据库中的项目永远不会超过 1 个:
public Optional<String> findByShortUrl(final String shortUrl){
List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
if(urlList.isEmpty()){
return Optional.empty();
}
else {
return Optional.of(urlList.get(0).getLongUrl());
}
}
I like the pattern of using a ShortUrlNotFoundException
if an item is not found.如果找不到项目,我喜欢使用
ShortUrlNotFoundException
的模式。 Should I use it also in findByShortUrl?我是否也应该在 findByShortUrl 中使用它? Then, findByShortUrl becomes:
然后,findByShortUrl 变为:
public Optional<String> findByShortUrl(final String shortUrl){
List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
if(urlList.isEmpty()){
throw new ShortUrlNotFoundException("URL not found for the given ID")
}
else {
return Optional.of(urlList.get(0).getLongUrl());
}
}
Why not using findFirst
as this:为什么不这样使用
findFirst
:
Optional<Url> findFirstByShortUrlIs(String shortUrl);
and then, you call:然后,你打电话:
public Optional<String> findByShortUrl(final String shortUrl){
return urlRepository.findFirstByShortUrlIs(shortUrl)
.map(Url::getLongUrl)
.map(Optional::of)
.orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}
Personally speaking, I would never use exception mechanism for both cases.就个人而言,我绝不会在这两种情况下都使用异常机制。 Exceptions are designed for unexpected situations that aren't covered by conventional business logic.
异常是为常规业务逻辑未涵盖的意外情况而设计的。 For example, findById should throw an exception for the search if and only if you do not expect that item in the database.
例如,当且仅当您不希望数据库中有该项目时,findById 应该为搜索抛出异常。 The same story for the findByShortUrl.
findByShortUrl 的情况相同。 As far as I understand it's a normal case not to have a object in db, thus it should be expected case to have empty result.
据我了解,在数据库中没有 object 是正常情况,因此应该预料到结果为空。 On other hand, you've mentioned that "there should never be more than 1 item in the DB", and that's the perfect case for an exception, If you see that return result set has more than 2 objects.
另一方面,您已经提到“数据库中的项目永远不应该超过 1 个”,如果您看到返回结果集有超过 2 个对象,那么这是异常的完美案例。 so go and thrown an excpetion.
所以 go 并引发了异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.