views:

285

answers:

2

Is there a way to globally handle exceptions for a Windows Service? Something similar to the following in Windows Forms applications:

Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);
+2  A: 

Have you tried

AppDomain.CurrentDomain.UnhandledException

This will fire for unhandled exceptions in the given domain no matter what thread they occur on. If your windows service uses multiple AppDomains you'll need to use this value for every domain but most don't.

JaredPar
A: 

Hi there,

Here is some pretty robust code we advise people to use when they're implementing http://exceptioneer.com in their Windows Applications.

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);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        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
        }

    }
}

Thanks,

Phil.

Plip