Home > Back-end >  How to use TryCatch Statement in ToDictionary C#?
How to use TryCatch Statement in ToDictionary C#?

Time:05-10

I have a dictionary of asyncronous call . The problem is sometimes these asyncronous call will throw an exception but I am not entirely sure how to handle them . The GetUserLicenseTypes returns a list so if I do get an exception I still want to return an empty list.

var tasks = allCompanyUsers.ToDictionary(
                u => u.Id,
                u => _subscriptionService.GetUserSubscription(companyId, u.Id));

            await Task.WhenAll(tasks.Values);

            var licenseListByUserId = tasks.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Result);

The code below doesn't work but I wanted to do something like this

var tasks = allCompanyUsers.ToDictionary(
                u => u.Id,
                u => {
try{
     return _subscriptionService.GetUserSubscription(companyId, u.Id);
}catch{
     return new List<string>();
}
});

            await Task.WhenAll(tasks.Values);

            var licenseListByUserId = tasks.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Result);

Note : I have gotten feedback that I should just avoid exception all together but at the moment it is hard to do considering that the GetUserSubscription function is already used in many location so the typical convention our application use is a trycatch statement to handle these thrown error.

CodePudding user response:

It looks as the type of the values of your dictionary is Task<List<string>>, but in your catch block you return a List<string>. If you return a task, it should work:

var tasks = allCompanyUsers.ToDictionary(
u => u.Id,
u =>
{
   try
   {
        return _subscriptionService.GetUserSubscription(companyId, u.Id);
   }
   catch
   {
        return Task.FromResult(new List<string>());
   }
});

CodePudding user response:

Here's one way:

async Task<IEnumerable<string>> GetSubscriptions(Id id)
{
    try { return await _subscriptionService.GetUserSubscription(companyId, id); }
    catch { return new List<string>(); }
}

var idsWithSubscriptions = await Task.WhenAll(allCompanyUsers
    .Select(async u => (
        u.Id,
        Subscription: await GetSubscription(companyId, u.Id)));

var licenseListByUserId = idsWithSubscriptions.ToDictionary(
    iws => iws.Id
    iws => iws.Subscription);

Because the Task<string> returned from GetUserSubscription is awaited, it will unwrap and throw any Exception, meaning the value in the catch block will be returned.

  • Related