Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Iterator Exception Handling

var trimmed = myStringArray.Select(s => s.Substring(0, 10));

If one of the strings isn't 10 characters long I'd get an ArgumentOutOfRangeException.

In this case its fairly trivial to find out and I know I can do

s.Substring(0, Math.Min(10, s.Length))

With more complex object construction errors like this aren't always easy to see though. Is there a way to see what string wasn't long enough via exception handling?

like image 714
kwcto Avatar asked Nov 05 '22 15:11

kwcto


1 Answers

Create a method that does the complex transformation that can throw exceptions and call it from the lambda. e.g. .Select(s => complexMethod(s))

string complexMethod(string s)
{
  try
  {
    ...
    return ...
  }
  catch
  ...
}

Now you can log the exception within the catch block before re-throwing, or use Exception.Data to add information to it before re-throwing, or wrap it in a custom exception with the information you need. Remember to use just 'throw' when you re-throw it if it's not a custom exception.

You can also put the method body inline in the lambda: .Select(s => { ... return ...})

like image 87
Ian Mercer Avatar answered Nov 14 '22 21:11

Ian Mercer