Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter validation in "async"/"await" methods should be wrapped

Tags:

c#

sonarqube

Why is SonarQube complaining in this code? I read explanation, but din't really understand why and what I need to do, to make it go away.

Link to SonarQube Rule

public async Task Add(SomeModel obj)
{
    if (obj == null)
    {
        throw new ArgumentNullException(nameof(obj));
    }
    var obj2 = new OtherObject();
    obj2.UpdateWith(obj);
    await _localDatabaseService.AddAsync(obj2);
}

Changing code to look like this does not resolve issue.

public Task Add(SomeModel obj)
{
    if (obj == null)
    {
        throw new ArgumentNullException(nameof(obj));
    }
    return AddInternal(obj);
}
private async Task AddInternal(SomeModel obj)
{
    var obj2 = new OtherObject();
    obj2.UpdateWith(obj);
    await _localDatabaseService.AddAsync(i);
}
like image 391
Ammar Hadzic Avatar asked Jun 12 '18 14:06

Ammar Hadzic


1 Answers

I just tried your examples and the issue isn't raised on your second code (replacing AddAsync(i) with AddAsync(obj2) to match first code logic.

Regarding the explanation of the rule I think the website is pretty clear but let me provide a code sample to try and illustrate the wrong behavior.

static async void Main(string[] args)
{
    var x = new Program().Add(null); // Exception is not raised here...

    // do some other things

    await x; // ... but here when awaited
}

As you can see the issue isn't raised when you expect it.

Obviously, if you are sure that you NEVER end up in this kind of situation and that no-one would use your method in this way you can turn-off the rule.

like image 199
Amaury Levé Avatar answered Oct 15 '22 23:10

Amaury Levé