'response' 在 SonarQube 中的至少一个执行路径上为空
'response' is null on at least one execution path in SonarQube
第一次使用SonarQube来分析代码。我有一种方法如下。
public async Task<HttpResponseMessage> SendRequest(HttpRequestMessage httpRequest)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = null;
response = await client.SendAsync(httpRequest);
if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout || response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
{
//DoSomething
}
else
{
// DoSomethingElse
}
}
现在当我 运行 SonarQube 时,它指向 if 条件并将其显示为错误。消息是"'response' is null on at least one execution path."
。我如何删除这个 bug.Does,这意味着整个 if/else 块应该包含在另一个 if 条件中,例如 if (response != null){}
。任何 help/explaination 表示赞赏。
虽然极不可能,但 await client.SendAsync
有可能 return null 并且分析器希望您对变量进行空检查。
接下来,避免为每个请求创建一个新的 HttpClient
实例,因为这会耗尽套接字。尽可能重复使用静态实例(Singleton)。
static HttpClient client = new HttpClient();
public async Task<HttpResponseMessage> SendRequest(HttpRequestMessage httpRequest) {
var response = await client.SendAsync(httpRequest);
if(response == null) throw new InvalidOperationException();
if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout ||
response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
) {
// DoSomething
} else {
// DoSomethingElse
}
return response;
}
第一次使用SonarQube来分析代码。我有一种方法如下。
public async Task<HttpResponseMessage> SendRequest(HttpRequestMessage httpRequest)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = null;
response = await client.SendAsync(httpRequest);
if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout || response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
{
//DoSomething
}
else
{
// DoSomethingElse
}
}
现在当我 运行 SonarQube 时,它指向 if 条件并将其显示为错误。消息是"'response' is null on at least one execution path."
。我如何删除这个 bug.Does,这意味着整个 if/else 块应该包含在另一个 if 条件中,例如 if (response != null){}
。任何 help/explaination 表示赞赏。
虽然极不可能,但 await client.SendAsync
有可能 return null 并且分析器希望您对变量进行空检查。
接下来,避免为每个请求创建一个新的 HttpClient
实例,因为这会耗尽套接字。尽可能重复使用静态实例(Singleton)。
static HttpClient client = new HttpClient();
public async Task<HttpResponseMessage> SendRequest(HttpRequestMessage httpRequest) {
var response = await client.SendAsync(httpRequest);
if(response == null) throw new InvalidOperationException();
if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout ||
response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
) {
// DoSomething
} else {
// DoSomethingElse
}
return response;
}