0

I would like to catch unhandled exceptions in a windows service application in the class that inherits from ServiceBase class. I have already tried incorporating the code:

AppDomain.CurrentDomain.UnhandledException += (s, e) =>
        {
            var exception = (Exception)e.ExceptionObject;
            Log.Error("Unhandled exception", exception);
        };

But that doesn't work.

Claritta
  • 189
  • 1
  • 4
  • 17
  • Possible duplicate of [unhandled exceptions in a windows service](http://stackoverflow.com/questions/10609443/unhandled-exceptions-in-a-windows-service) – Ken White Dec 27 '16 at 14:39

1 Answers1

0

Try this:

// Starts the application. 
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
    // Add the event handler for handling non-UI thread exceptions to the event. 
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    // Runs the application.
    Application.Run(new ErrorHandlerForm());
}

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";

        // Since we can't prevent the app from terminating, log this to the event log.
        if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        try
        {
            MessageBox.Show("Fatal Non-UI Error",
                "Fatal Non-UI Error. Could not write the error to the event log. Reason: "
                + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
}

You also can take a look at this example: https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx

NicoRiff
  • 4,803
  • 3
  • 25
  • 54