1

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.

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • What if you declare and initialize the response object in one line only? – Rui Jarimba Jul 23 '18 at 07:37
  • @RuiJarimba The same message is shown. No difference. – CrazyCoder Jul 23 '18 at 07:40
  • 1
    For a reason I do not know, looks like `await client.SendAsync(httpRequest)` is returning null. I would suggest writting a `if (response == null) { // DoUnspected Error }` before checking its properties (the StatusCode) – Cleptus Jul 23 '18 at 08:04

1 Answers1

1

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;
 }
Nkosi
  • 235,767
  • 35
  • 427
  • 472