【问题标题】:optional orElseThrow gives null pointer exception可选的 orElseThrow 给出空指针异常
【发布时间】: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&lt;Optional&lt;Tenant&gt;&gt;.. . 还是我错过了什么?

标签: java nullpointerexception optional


【解决方案1】:

如果您的意思是 tenantRepository.findById(id) 有时会返回 null,我会按照以下方式进行调整。

public Optional<Tenant> findTenantById(String id) {
    return Optional.ofNullable(tenantRepository.findById(id));
}

【讨论】:

    【解决方案2】:

    myy jpa 实现存在问题,正如你们中的许多人所提到的,链中的一种方法是抛出 null。感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 2014-09-06
      • 2014-07-19
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多