Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching the .net debugger while still providing useful logging on death

I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.

Something along the lines of

static void Main () {
    if (Debugger.IsAttached)
        RunApp();
    else {
        try {
            RunApp();
        }
        catch (Exception e) {
            LogException(e);
            throw;
        }
    }
 }

While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.

Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.

Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?

like image 514
C. Broadbent Avatar asked Oct 17 '08 10:10

C. Broadbent


1 Answers

As Paul Betts already mentioned, you might be better off using the AppDomain.UnhandledException event instead of a try/catch block.

In your UnhandledException event handler you can log/display the exception and then offer the option to debug e.g. show a form with the exception details and buttons to ignore, debug or quit.

If the user selects the debug option, call System.Diagnostics.Debugger.Break() which allows the user to attach whatever debugger they want with the full call stack still available.

Obviously, you could disable this option for any builds you know you're not ever going to be attaching the debugger to.

class Program
{
    static void Main()
    {
        AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;

        RunApp();
    }

    static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        Console.WriteLine(e.ExceptionObject);
        Console.WriteLine("Do you want to Debug?");
        if (Console.ReadLine().StartsWith("y"))
            Debugger.Break();
    }

    static void RunApp()
    {
        throw new Exception();
    }
}
like image 50
Leaf Garland Avatar answered Oct 12 '22 13:10

Leaf Garland