是否可以使用Optional重写以下内容?在我看来,当情况需要抛出异常时,使用Optional可能不是一个好主意?
Item item = service.get(id);
if (item == null) {
throw new ItemNotFoundException();
}
item.setValue(false);
itemDao.update(item);
尝试1:
Optional.ofNullable(service.get(id))
.ifPresent(item -> {
item.setValue(false);
itemDao.update(item);
}); // cannot throw exception inside the consumer
尝试2:
Optional.ofNullable(service.get(id))
.map(item -> {
item.setValue(false);
itemDao.update(item);
})
.orElseThrow(new ItemNotFoundException()); //can throw exception here but the usage of map is not correct
最佳答案
正如之前的答案中提到的 - 服务方法应该返回一个可选值。
如果您绝对想在未更改的服务方法中使用Optional
,请按以下步骤操作:
Item item = Optional.ofNullable(service.get(id)).orElseThrow(ItemNotFoundException::new);
item.setValue(false);
itemDao.update(item);
关于java - 在Optional中使用consumer并抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68844342/