Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make VS break on exceptions in an async Task, without breaking on all exceptions?

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).

like image 687
user247702 Avatar asked Sep 23 '13 12:09

user247702


People also ask

How do I stop Visual Studio from breaking on exception?

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 .

What happens if an exception is thrown within an asynchronous method?

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.

How do I create a break on exception in Visual Studio?

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.


2 Answers

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.

like image 114
CodeMonkeyForHire Avatar answered Oct 09 '22 14:10

CodeMonkeyForHire


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.

like image 22
CSharpie Avatar answered Oct 09 '22 14:10

CSharpie