有没有更干净的方法在这里使用 Optional 而不在三个地方返回 "NA" ?

Is there a cleaner way to use Optional here without returning "NA" in three places?

    public String getSanitisedMessage() {

        Throwable rootCause = context.getRootCauseException();
        if(rootCause != null) {
            return Optional.ofNullable(rootCause.getMessage())
                    .map(message -> Stream.of(
                            // clean message substrings we want to find
                            "Connection timed out",
                            "Connection reset",
                            "Connection was lost",
                            "FTP Fails"
                    ).filter(subString -> message
                            .toLowerCase()
                            .contains(subString.toLowerCase())
                    ).findFirst().orElse("NA")
                    ).orElse("NA");
        } else return "NA";

    }

objective 是检查 Throwable 的消息中的子字符串,如果找到则 return 子字符串,否则 return NAcontext.getRootCauseException()Throwable.getMessage() 调用都可以 return null.

一种可能的方法是使用 flatMapfindFirst 而不是 map 作为:

// method argument is just for the sake of an example and clarification here 
public String getSanitisedMessage(Throwable rootCause, Set<String> primaryCauses) {
    return Optional.ofNullable(rootCause)
            .map(Throwable::getMessage)
            .map(String::toLowerCase)
            .flatMap(message -> primaryCauses.stream()
                    .map(String::toLowerCase)
                    .filter(message::contains)
                    .findFirst())
            .orElse("NA");
}

或者也可以使用三元运算符表示为:

return rootCause == null || rootCause.getMessage() == null ? "NA" :
        primaryCauses.stream().map(String::toLowerCase).filter(subString -> rootCause.getMessage()
                .toLowerCase().contains(subString)).findFirst().orElse("NA");

我想你应该在这里抛出一个异常,并正确处理它(看来你稍后要检查字符串)。 如果你想坚持这种方式,你可以为你的 context.getMessage() 添加一个默认值(假设这是一个自定义 class 实现 Context ),并且 return 它的值。

否则,您还可以执行以下操作:

 Throwable rootCause = context.getRootCauseException();
    if (rootCause != null) {
        return Stream.of("Connection timed out",
                "Connection reset",
                "Connection was lost",
                "FTP Fails")
                     .filter(s -> s.equalsIgnoreCase(rootCause.getMessage()))
                     .findFirst()
                     .orElse("NA");
    }
    return "NA";
 }