Google+ Peter Bromberg's .NET Blog | Global Unhandled Exception Logging

Peter Bromberg's .NET Blog All Things Programming

Global Unhandled Exception Logging

28. November 2016 08:53 by admin in C#, EXCEPTIONS

We as developers often don't account for the fact that we may not be catching and handling all possible exceptions.This is particularly problematic in Windows Services as if something bad happens, the service may continue running but will be in a state where it isn't actually "doing anything".

Code like the following can be used to catch and handle any exception for which no handler has been wired in, and such exceptions can be logged using your preferred method:

 

namespace YourNamespace {

static class Program

{

[STAThread]

static void Main()

{

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)

{ HandleException(e.Exception);

}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

HandleException((Exception)e.ExceptionObject);

}

static void HandleException(Exception e)

{

//Handle your Exception here

}

}

}

Add comment

  Country flag


Loading