Global Error handling

iebidan

Contributor
Joined
Feb 6, 2003
Messages
484
Is there a way to create a global error handler for Windows Forms, I want to add to my app an error watcher, when an error ocurrs get the exception and send it thru mail to solve the problem.
I will like to have this error watcher running on a secondary thread... is this possible?????
 
You can use the two following events for uncaught exceptions:

[*]UnhandledException
[*]ThreadException

UnhandledException is in the Domain object and can be used for CLR type exceptions where as the latter will catch unhandled Forms exceptions.

For example, in your form code bootstrap you can use something like this:
C#:
[STAThread]
static void Main() 
{
   AppDomain curr_domain = AppDomain.CurrentDomain;
      
   curr_domain.UnhandledException += 
      new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

   Application.ThreadException +=
      new ThreadExceptionEventHandler(ThreadExceptionHandler);

   Application.Run(new The_App());
}

and your handlers look like:

C#:
// do whatever handling you need
private static void UnhandledExceptionHandler(
   object sender,
   UnhandledExceptionEventArgs args)
{
   Exception e = (Exception)args.ExceptionObject;		
   MessageBox.Show("drat " + e.Message);
}

// do what ever handling you need
private static void ThreadExceptionHandler(
   object sender, 
   ThreadExceptionEventArgs args)
{
   Exception e = (Exception)args.Exception;
   MessageBox.Show("oops :: " + e.Message);
}

Interesting note is the inconsistent naming scheme in the EventArgs, in UnhandledExceptionEventArgs the exception is in the ExceptionObject property where as with the ThreadExceptionEventArgs is in the Exception property. That must have slipped through any code reviews!

Also, you will need to change a reg key:

HKLM/Software/Microsoft/.NetFramework/DbgJITDebugLaunchSetting to a value other than 2.
 
I have a dll I created which I call when an error occurs. It displays to the user where the error occured and the text of the error. The form displays the application name which called the dll. The form also includes a button to which send the error details to the user name(s) passed to the dll.

Works a treat for me :-)
 
Back
Top