0

I've installed the nuget package for Elmah.WebApi and elmah.Mvc, which is catching a lot of my errors. However I have a parallel foreach loop which is throwing an error and not being caught/logged by elmah.

I assumed the nuget packages would implement the classes and interface specified here: http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling

Is there an additional filter you need to apply to catch errors that occur in separate threads? I'm guessing the same applies when using async/await?

Here is my code:

Parallel.ForEach(serviceHeaders, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, patientGroup =>
{
    ...
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Phil
  • 1,609
  • 12
  • 24
  • Sounds like the exception occurs after returning. How do you run your "parallel loop"? Does it use `await` or do you queue it on the thread pool? If you queue it, Elmah won't catch it. – Benjamin E. Jul 02 '15 at 10:03
  • Hi benjamin, I've added how I run the parallel loop. I thought that the error would bubble back up through the calling methods etc and be caught by elmah. Is this not the case? – Phil Jul 02 '15 at 10:07

2 Answers2

1

If you register Elmah in Web API as an IExceptionLogger (probably done automatically by the Nuget package), it requires the HttpContext of the current main thread. As soon as that context is gone, i.e. you return to the client, no more exceptions will be caught.

You might be able to use Elmah for manual logging without the request context, but the correct way to solve this is to use distributed systems such as Azure WebJobs, queues/messaging systems etc.

If you don't want to go that far, it might be better to await the async operations and Elmah will catch exceptions.

More info here.

Community
  • 1
  • 1
Benjamin E.
  • 5,042
  • 5
  • 38
  • 65
0

Turns out that elmah does catch the errors raised within the parallel threads. Each error is added to AggregateException as each thread could in theory throw errors at the same time. More info can be found here: https://msdn.microsoft.com/en-us/library/dd460695(v=vs.110).aspx

However, the issue I'm having is something completely unrelated to my question!

Phil
  • 1,609
  • 12
  • 24