Java API返回可选

我正在与API通信,并且已经利用了Optional类的使用。但是我觉得错误处理可能会更优雅,因此,关于如何改进此错误的任何建议都将受到欢迎。我是否还在实际的api调用中缺少异常处理?

public Optional<account> getGreenqloudaccount(String accountUUid) {
    System.out.println("tmplog: GreenqloudaccountDao->getGreenqloudaccount");
    for (account account : apiClient.accountList()) {
        if (account.getUuid().equals(accountUUid)) {
            System.out.println("getGreenqloudaccount,account: " + account.toString());
            return Optional.of(account);
        }
    }
    return Optional.empty();
}

public Optional<String> getMarketplaceCustomerIdByusername(String username) {
    if (username == null || username.equals("")) {
        return Optional.empty();
    }
    AwsMarketplace marketplaceData = apiClient.getMarketplaceData(getKeys(username));
    if (marketplaceData == null) {
        return Optional.empty();
    }
    return Optional.ofNullable(marketplaceData.getObjects().get(0).getcustomerId());
}

private Pair getKeys(String username) {
    GetKeys getKeys = apiClient.getKeys(username);
    return new Pair(getKeys.getapiPrivateKey(),getKeys.getapiPublicKey());
}
GUSHANZHUJU 回答:Java API返回可选

代码的主要问题:您将许多非常不同的结果扔到了同一“存储桶”中。

例如,

getMarketplaceCustomerIdByUsername()在以下情况下返回空的Optional:

  • 用户名为空
  • 用户名是“”(考虑一下""意味着空,但是" "却不是空吗?!)
  • 找不到给定用户的AwsMarketplace实例

如前所述,这是非常的不同问题。第一个可能表明:提供的用户名不正确,因此您应将其告知用户。最后一个意思是:“有些东西是可疑的,也许用户是未知的,或者发生了其他事情”。

因此:考虑不要将不同的结果减少为一个空的Optional。而是考虑抛出(不同?)异常。当“无结果”是操作的有效结果时,可以使用Optional。但是“没有结果,因为错误的用户名”感觉上不是有效的结果。

,

您可以使用Optional.isPresent()

使用支票

使用Optional.orElseThrow(Supplier<? extends X> exceptionSupplier)

阅读有关可选here

的JDK8文档

另外,您可能需要在检查空字符串之前修整输入参数

,

如果您要处理极端情况,则可以像使用第一种方法那样使用findFirst来提高代码的可读性,例如:

public Optional<Account> getGreenqloudAccount(String accountUUid) {
    System.out.println("tmplog: GreenqloudAccountDao->getGreenqloudAccount");
    return apiClient.accountList().stream()
            .filter(account -> account.getUuId().equals(accountUUid))
            // you can 'peek' and log 
            .findFirst(); // you return the first account or empty 
}

继续使用其他API,请注意Optional.map处理返回null值并隐式返回Optional.empty的操作。因此,您可以使用:

public Optional<String> getMarketplaceCustomerIdByUsername(String username) {
    return Optional.ofNullable(username) // if username is null empty
            .filter(name -> !name.isEmpty()) // empty string returns filtered out
            .map(name -> apiClient.getMarketplaceData(getKeys(name))) // handles 'null' calue returned
            .map(marketplaceData -> marketplaceData.getObjects().get(0).getCustomerId()); // here as well
}
本文链接:https://www.f2er.com/3108654.html

大家都在问