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
消息中的子字符串,如果找到,则返回子字符串,否则返回NA
。
context.getRootCauseException()
和Throwable.getMessage()
调用都可以返回null
# 1 楼答案
在我看来,您应该在这里抛出一个异常,并正确地处理它(看起来您稍后要检查字符串)。 如果你想坚持这样做,你可以在你的上下文中添加一个默认值。getMessage()(假设这是一个实现上下文的自定义类),并返回其值
否则,您还可以执行以下操作:
# 2 楼答案
一种可能的方法是使用
flatMap
和findFirst
而不是map
作为:或者三元运算符也可以用来表示: