Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While debugging, can I view object causing exception in LINQ?

Lets say I have this code:

IDictionary<int, int> itemPriceDict = loadItemPriceDictionary();
IList<IRow> dbItems = loadItemsFromDatabase();

IList<ItemDTO> itemDTOs = dbItems
    .Select(dbItem => new ItemDTO()
    {
        Id = dbItem.Id,
        Label = dbItem.Label,
        PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
    })
    .ToList();

and I sometimes get an KeyNotFound exception when given price tag does not exist for the given dbItem.

Now, when debugging in Visual Studio and an exception is thrown, you can see StackTrace, TargetSite which show you what line of code triggered it, but is it possible to find out what object (dbItem) caused the exception and display it's data in Debugger? For example in Watch window?

I would like to:

  1. Either know which key was not present in the dictionary
  2. Or better yet know the key and also the dbItem processed in Select

But without any need to add or modify any code.

P.S.: I know I can rewrite the code as cycle, but I would like not to.

like image 305
Tomas Stibrany Avatar asked May 02 '26 04:05

Tomas Stibrany


2 Answers

You could write your Select as such :

.Select(dbItem => 
    {
        return new ItemDTO()
        {
            Id = dbItem.Id,
            Label = dbItem.Label,
            PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
        })
    }
    .ToList();

That would allow you to place breakpoints inside the select evaluations.

Better yet, go in the Debug Menu, then select Exceptions (it is under the Windows submenu on my Visual Studio Edition).

Then set it up so that it breaks on either KeyNotFoundException or any exception of your choice.

The debugger will then automatically break when an exception occurs allowing you to inspect the state of the related objects

like image 138
Sidewinder94 Avatar answered May 04 '26 19:05

Sidewinder94


[disclaimer: I work at OzCode]

Have you tried OzCode. Linq debugging support was added to the EAP and one of the features is that it can predict if a query will throw an exception and show the offending item.

enter image description here

This way you don't need to dissect your code or try and debug it in your head.

like image 45
Dror Helper Avatar answered May 04 '26 20:05

Dror Helper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!