[英]Sonar Change this condition so that it does not always evaluate to “true”. False positive
[英]Why does sonar think this expression is always false
在我的 Java 項目 SonarQube 中說表達式總是錯誤的。 但是我不明白為什么。 這是有問題的代碼:
BaseException baseException = null;
for (SpaceInfo i: spaceInfos) {
try {
processSingle(i.getSpaceKey(), i.getContentType());
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
}
// Here sonar say that this condition will always evaluate to false.
if (baseException != null) {
throw baseException;
}
但是在我看來,如果processSingle
方法拋出BaseException
那么baseException
不應該是 null ,因此表達式不應該評估為假。
processSingle 方法聲明如下:
private void processSingle(String spaceKey, String contentType) throws BaseException
並且肯定存在processSingle
方法會拋出BaseException
的情況。 所以我認為Sonar是錯誤的。 或者這里發生了什么我沒有看到的事情?
更新:
這就是BaseException.chain()
所做的:
public static BaseException chain (BaseException a, BaseException b) {
if (a == null) { return b; }
a.setNextException(b);
return a;
}
這是processSingle
的代碼:
private void processSingle(String spaceKey, String contentType) throws BaseException {
assert ContentTypes.Page.equals(contentType) || ContentTypes.BlogPost.equals(contentType);
Content content;
try {
content = createEmptyContent(spaceKey, contentType);
} catch (Exception e) {
throw new MessageToContentProcessorProcessSingleException(contentType, spaceKey, e);
}
BaseException baseException = null;
try {
contentCreator.addMetadata(content);
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
Pair<List<AttachmentInfo>, FailedToSaveAttachmentException> pair = contentCreator.saveAttachments(messageParser.getContent(), content);
List<AttachmentInfo> attachments = pair.getLeft();
baseException = BaseException.chain(baseException, pair.getRight());
try {
String html = htmlGenerator.generateHtml(attachments, messageParser.getContent());
contentCreator.updateBodyOfContent(content, html);
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
if (baseException != null) {
throw new MessageToContentProcessorProcessSingleException(contentType, spaceKey, baseException);
}
}
只是為了測試/好奇,我會嘗試:
} catch (BaseException e) {
baseException = e;
}
這將顯示 Sonar 是否認為可以拋出異常。 或者,如果它被chain
方法或賦值語句弄糊塗了(賦值給basseException
但在賦值的右側使用它(仍然為空))。
我知道這是在改變邏輯,只是為了測試
甚至嘗試(但我不相信這會欺騙聲納)
} catch (BaseException e) {
var tmp = BaseException.chain(baseException, e);
baseException = tmp;
}
嘗試更改chain()
以幫助 SonarQube:
public static BaseException chain (BaseException a, BaseException b) {
if (a == null) {
return b;
} else {
a.setNextException(b);
return a;
}
}
想一想,幾乎不可能是問題 - 在這里a
不是null
幾乎是微不足道的
我會嘗試看看它是否有效:
BaseException baseException;
for (SpaceInfo i: spaceInfos) {
try {
processSingle(i.getSpaceKey(), i.getContentType());
baseException = null;
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.