Search code examples
c#debuggingasync-awaituwpunhandled-exception

Exceptions debugging with async and UWP


I'm working on the UWP application. And I'm using async/await a lot. Always when an exception occurs in my code the debugger set break in App.g.i.cs

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
            UnhandledException += (sender, e) =>
            {
                if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
            };
#endif

But I want to see the line when the exception occured. How to achieve that behavior ?


Solution

  • Add the following method to your App class:

    private static void UnhandledError(object sender, UnhandledErrorDetectedEventArgs eventArgs)
    {
        try
        {
            // A breakpoint here is generally uninformative
            eventArgs.UnhandledError.Propagate();
        }
        catch (Exception e)
        {
            // Set a breakpoint here:
            Debug.WriteLine("Error: {0}", e);
            throw;
        }
    }
    

    In your App constructor:

    public UnitTestApp()
    {
        CoreApplication.UnhandledErrorDetected += UnhandledError;
    
        // ...and any other initialization.
        // The InitializeComponent call just sets up error handlers,
        // and you can probably do without in the case of the App class.
    
        // This can be useful for debugging XAML:
        DebugSettings.IsBindingTracingEnabled = true;
        DebugSettings.BindingFailed +=
            (sender, args) => Debug.WriteLine(args.Message);
    
    }
    

    There are still cases where you don't get a good stack trace, but this is often helpful.

    Another approach is to break when an exception is thrown (via Debug, Windows, Exception Settings).