【发布时间】:2020-05-07 10:00:32
【问题描述】:
我有这个方法:
public Tenant getTenant(String tenantId) throws TenantNotFoundException {
return tenantDatabaseService.findTenantById(tenantId)
.orElseThrow(() -> new TenantNotFoundException("Tenant not found"));
}
tenantDatabaseService.findTenantById(tenantId) 返回一个Optional:
public Optional<Tenant> findTenantById(String id) {
return tenantRepository.findById(id);
}
当findById 为空时,我希望抛出异常。
相反,我看到NullPointerException 被抛出:
Failed to complete request: java.lang.NullPointerException: while trying to invoke the method
java.util.Optional.orElseThrow(java.util.function.Supplier) of a null object returned from
com.sap.gb.service.TenantDatabaseService.findTenantById(java.lang.String)
这里有什么帮助吗?
【问题讨论】:
-
您的链中的一个方法返回 null 而不是可选的。
-
能否请您添加异常的堆栈跟踪
-
新的 nullpointerexception 描述消息非常明显:
findTenantById()返回 null 而不是空的 optional -
Repository#findById的声明是什么? -
@ernest_k 我删除了它,因为如果
findById没有被声明为返回Optional会导致编译错误,所以findTenantById会返回Optional<Optional<Tenant>>.. . 还是我错过了什么?
标签: java nullpointerexception optional