Search code examples
c#azureexceptionazure-devopsconsole.writeline

Handling Exceptions (Null?) in Console.Writeline content


There has to be a better way to do this?! I was messing around with ?. etc but could not figure out the proper context for it. I need to add several more items to the console output, so adding several more nested try-catch is daunting yet do-able. would have to handle 4 different items that might throw exceptions.

Perhaps, I should be building up the string piece by piece before the writeline statement?

"for now" I have this mess:

foreach (WorkItem workItem in workItems){
// write work item to console
try  // ideal both assigned and tagged
{
    Console.WriteLine("{0} {1} {2} {3} {4} {5}", workItem.Id, 
    workItem.Fields["System.Title"], workItem.Fields["System.WorkItemType"], 
    workItem.Fields["System.AssignedTo"], workItem.Fields["System.State"], 
    workItem.Fields["System.Tags"]);
}
catch (Exception) // at least one not correct, maybe two
{
    try  // is it the assigned?
    {
        Console.WriteLine("{0} {1} {2} {3} {4} {5}", workItem.Id, 
        workItem.Fields["System.Title"], 
        workItem.Fields["System.WorkItemType"], "Unassigned", 
        workItem.Fields["System.State"], workItem.Fields["System.Tags"]);
    }
    catch (Exception)
    {
        try // is it the tags?
        {
            Console.WriteLine("{0} {1} {2} {3} {4} {5}", workItem.Id, 
            workItem.Fields["System.Title"], 
            workItem.Fields["System.WorkItemType"], 
            workItem.Fields["System.AssignedTo"], 
            workItem.Fields["System.State"], "NoTags");

        }
        catch (Exception)  // its both
        {
            Console.WriteLine("{0} {1} {2} {3} {4} {5}", workItem.Id, 
            workItem.Fields["System.Title"], 
            workItem.Fields["System.WorkItemType"], "Unassigned", 
            workItem.Fields["System.State"], "NoTags");
        }
    }
}

}


Solution

  • Base on the discussion of the comments. I would like to summary the solution as below. Thank juharr and Selvin for sharing ideas.

    1,Since Fields.Contains("") throws the error. You can use workItem.Fields.ContainsKey(). The the example code is as below:

    workItem.Fields.ContainsKey("name") ? workItem.Fields["name"] : "default"
    

    2, use TryGetValue()

    workItem.Fields.TryGetValue("System.AssignedTo", out Object identityOjbect)? identityOjbect:"not exist"