Search code examples
c#httpresponsemessage

Fixing a Sonarqube bug regarding HttpResponseMessage in c#


I have code something like this:

HttpResponseMessage response = new HttpResponseMessage();
try
{
    string url = ConfigurationManager.AppSettings["url"];
    using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url))
    {
        requestMessage.Headers.Add("Accept", "application/json");                                
        response = await SendHttpRequest(requestMessage).ConfigureAwait(false);                                
    }
    if (response != null && response.IsSuccessStatusCode)
    {
        // do other things
    }
    else
    {
        log.Error("Http response failure with Status Code : " + response.StatusCode"); // sonarqube showing a bug here
    }
}
catch (Exception ex2)
{
    // log the exception                        
}


public virtual async Task<HttpResponseMessage> SendHttpRequest(HttpRequestMessage httpRequest)
{
    HttpResponseMessage response = null;
    using (HttpClient client = new HttpClient())
    {
        response = await client.SendAsync(httpRequest).ConfigureAwait(false);
    }
    return response;
}

When I run Sonarqube analysis on this code, it is throwing a bug at the commented line in the code, saying "'response' is null on at least one execution path" How can I make this go away. I have intialized HttpResponseMessage , but still this is throwing a bug.
Any help in this regard will be helpful.


Solution

  • Please check the below code

     if (response != null && response.IsSuccessStatusCode)
    {
        // do other things
    }
    else
    {
        log.Error("Http response failure with Status Code : " + response.StatusCode"); // sonarqube showing a bug here
    }
    

    In your code SonarQube thinks that there are chances of null reference exception at response.StatusCode because in if condition you checked it for not null. IF it is null then it will go to else where you are accessing property of null object.

    Just to resolve the SonarQube error please update your line with below

    log.Error("Http response failure with Status Code : " + response?.StatusCode"); // sonarqube showing a bug here
    

    Hopefully this will work