title: Catching unhandled exceptions with asp.net webapi and TPL
body: <p>I have a scenario, where I create <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx" rel="nofollow noreferrer">Tasks</a> as a part of a Webapi call. When an exception happens in a task it does not get caught and I can't figure out how to implement a global exception handler for this.</p>
  
  <p>In particular: </p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/16028919/catch-all-unhandled-exceptions-in-asp-net-web-api">This question</a> and the solution for <a href="https://aspnetwebstack.codeplex.com/wikipage?title=Global%20Error%20Handling" rel="nofollow noreferrer">Web API Global Error Handling</a> does not work for Tasks. I'm guessing because these are executed on threads webapi has no awareness of.</li>
  <li>Subscribing to <a href="https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.110).aspx" rel="nofollow noreferrer">AppDomain.UnhandledException</a> Event <a href="https://stackoverflow.com/questions/29257188/webapi-and-unhandled-exception-hook-per-appdomain">does not work either</a>. Possibly because web host catches all the unhandled exceptions and is not letting them bubble up.</li>
  </ul>
  
  <p>If you believe that any of the above should work let me know, and I'll come up with a small reproducible example of what I'm observing. Otherwise, what is the right way of doing this, that would work?</p>
  
  <pre><code>[HttpGet]
  public IQueryable&lt;Thingies&gt; Thingies()
  {
      Task.Run(() =&gt; { throw new ApplicationException("How do I catch all of these globally?"); });
      return _db.Thingies;
  }
  </code></pre>
  
  <p>I also should note that the application does not have dependencies on <code>System.Web</code> and I would not like to introduce them.</p>