As indicated here and here, exceptions occuring in an async Task are technically not unhandled.
This is particularly nasty when working with MVC. It actually took us a while to figure out why it was occurring more and more that exceptions weren't being caught, we had been gradually introducing Web API calls to our aplication the past few weeks.
public async Task<ActionResult> Foo() { // ... }
The suggested workaround is to make VS break on all exceptions instead of only unhandled exceptions. It works, with the annoying 'side-effect' that it does indeed break on all exceptions :)
Is there another workaround that doesn't involve breaking on all exceptions? It can be specific to MVC but doesn't have to be (meaning if it's a general solution that happens to work for MVC).
To turn off stop on exceptions press " Ctrl + Alt + E ". This will open the Exceptions window . Untick "Common Language Runtime Exceptions - Thrown". That would prevent it from pausing from within the delegate, but not when it's rethrown on Wait .
As we know, in asynchronous programming, control does not wait for the function's result and it executes the next line. So when the function throws an exception, at that moment the program control is out of the try-catch block.
Tell the debugger to break when an exception is thrownIn the Exception Settings window (Debug > Windows > Exception Settings), expand the node for a category of exceptions, such as Common Language Runtime Exceptions. Then select the check box for a specific exception within that category, such as System.
A) Wrap your calls and throw a custom Exception in your Task code. Break on only throw of your custom exception. You can select the Exceptions for first throw.
B). Debug.Assert() your Task Results, if you have any wait code. i.e., not just firing and forgetting. Tasks return the Exceptions in a property if you wait on them somewhere or stick error handling in a continuation.
psuedo code i.e. task. continuewith(r => if(!r.Exception is null) Debug.Break())) etc.
Hope that helps you on the right path.
You could try and listen for this event if nothing else works here
AppDomain.CurrentDomain.UnhandledException
or
AppDomain.CurrentDomain.FirstChanceException
Then you need to put some if-constructs (check what sender for example) to hit your breakpoint only when it makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With