java - 在服务中引发异常时,哪种做法更好?
问题描述
我正在开发一个 Spring Boot CRUD RESTful API,我正在尝试定义做某些事情的最佳方式,例如:
这是我的 id端点服务列表用户:
@Service
public class DetailUserService {
@Autowired
UserRepository repository;
public Optional<User> listUser(Long id) {
Optional<User> user = repository.findById(id);
if (!user.isPresent()) {
throw new UserNotFoundException(id);
} else {
return repository.findById(id);
}
}
}
这是另一种写法:
@Service
public class DetailUserService {
@Autowired
UserRepository repository;
public User listUser(Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
两种方式都有效,但我怎么知道哪个更好?
解决方案
对于更少的代码和更易读的代码,使用java-8
总是一个更好的选择。
您可以使用您提到的以下类型作为您的第二个选项。使用该Optional.orElseThrow()
方法代表了另一种优雅的替代isPresent()-get()
方案
您可以在这里找到更多信息 https://dzone.com/articles/using-optional-correctly-is-not-optional
@Service
public class DetailUserService {
@Autowired
UserRepository repository;
public User listUser(Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
推荐阅读
- django - Django:在这种情况下如何使用聚合器
- ruby-on-rails - 在不重新加载页面的情况下显示表单错误消息
- azure-ad-verifiable-credentials - 是否存在针对 Microsoft Azure AD 可验证凭据的运行时定义声明
- microsoft-graph-api - {Client} 来自 "@microsoft/microsoft-graph-client" 而不是 {MSGraphClient } 来自 "@microsoft/sp-http";)
- amazon-web-services - 带有生菜客户端和 AWS 弹性缓存的 Spring 数据 redis
- sql-server - SQL Server - 根据数据输出 XML 节点结构
- php - 如何使用 php 从大文本文件中提取包含信息的值
- c# - 连接问题iot aws mqttclient .net c#
- kubernetes - 如何启用 Prometheus/Grafana 来显示我的 rabbitmq 指标?目前没有显示数据
- powerbi - Power BI 切片器格式以指示筛选器