有没有更简洁的方法在这里使用Optional而不在三个地方返回“NA”?

问题描述 投票:4回答:2
    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";

    }

目标是检查Throwable的子串的消息,如果找到则返回子串,否则返回NAcontext.getRootCauseException()Throwable.getMessage()电话都可以返回null

java optional
2个回答
4
投票

一种可能的方法是使用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");

0
投票

Imo你应该在这里抛出一个异常,并正确处理它(似乎你以后要检查String)。如果你想坚持这种方式,你可以在context.getMessage()中添加一个默认值(假设这是一个实现Context的自定义类),并返回它的值。

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

 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";
 }
© www.soinside.com 2019 - 2024. All rights reserved.