¿Hay una forma más limpia de uso opcional aquí sin volver "NA" en tres lugares?

conorgriffin:
    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";

    }

El objetivo es comprobar el Throwablemensaje de 's de subcadenas y si se encuentra a continuación, devolver la subcadena, de lo contrario volver NA. Tanto context.getRootCauseException()y las Throwable.getMessage()llamadas podrían regresar null.

también:

Una manera posible es utilizar flatMapcon findFirsten lugar de mapcomo:

// 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");
}

O un operador ternario también podría ser usado para representar como:

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

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=188637&siteId=1
Recomendado
Clasificación