[英]Java 8 optional: ifPresent return object orElseThrow exception
[英]optional orElseThrow gives null pointer exception
我有這個方法:
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
為 null 時,我希望拋出異常。 相反,我看到一個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)
這里有什么幫助嗎?
如果您的意思是tenantRepository.findById(id)
有時會返回null
我會采用以下方式進行調整。
public Optional<Tenant> findTenantById(String id) {
return Optional.ofNullable(tenantRepository.findById(id));
}
我的 jpa 實現存在問題,正如你們中的許多人所提到的,其中一種方法是拋出 null。 感謝所有的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.