有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有更干净的方法可以在这里使用Optional,而不在三个地方返回“NA”?

    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


共 (2) 个答案

  1. # 1 楼答案

    在我看来,您应该在这里抛出一个异常,并正确地处理它(看起来您稍后要检查字符串)。 如果你想坚持这样做,你可以在你的上下文中添加一个默认值。getMessage()(假设这是一个实现上下文的自定义类),并返回其值

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

     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";
     }
    
  2. # 2 楼答案

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