PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to use TryCatch Statement in ToDictionary C#?

 August 05, 2022     c#, exception, linq, try-catch     No comments   

Issue

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.


Solution

Here's one way:

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

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

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

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



Answered By - Johnathan Barclay
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing