0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solved my issue. Can you also may be help me in resolving this issues I posted : stackoverflow.com/q/58446681/8930751 or stackoverflow.com/q/58405873/8930751 . Many thanks in advance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.