Search code examples
c#sonarqubehttpresponsemessage

'response' is null on at least one execution path in SonarQube


I'm using SonarQube for the first time to analyse the code. I have one method as below.

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
    }
 }

Now when I run SonarQube, it is pointing to the if condition and shows it as a bug. The message is "'response' is null on at least one execution path.". How do i remove this bug.Does that mean this whole if/else block should be enclosed with in another if condition like if (response != null){}. Any help/explaination is appreciated.


Solution

  • Though highly unlikely, await client.SendAsync has the potential to return null and the analyser wants you to do a null check on the variable.

    Next, avoid creating a new instance of HttpClient for each request as this can exhaust sockets. Reuse a static instance (Singleton) as long as possible.

    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;
     }