Sylloge
A C# helper library
code/App/GlobalExceptionHandler.cs
Go to the documentation of this file.
00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 using System;
00017 using System.Collections.Generic;
00018 using System.Text;
00019 
00020 namespace Sylloge
00021 {
00022     public static class GlobalExceptionHandler
00023     {
00024         public delegate void ExceptionResult(Exception ex, string additional, System.Windows.Forms.DialogResult result);
00025         public static event ExceptionResult UserResultOnException;
00026 
00030         public static void InstallHandlers()
00031         {
00032             System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnThreadException);
00033             System.Windows.Forms.Application.SetUnhandledExceptionMode(System.Windows.Forms.UnhandledExceptionMode.CatchException);
00034             AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Sylloge.GlobalExceptionHandler.AppDomain_UnhandledException);
00035         }
00036 
00042         public static void OnThreadException(System.Object sender, System.Threading.ThreadExceptionEventArgs ThreadExceptionEventArgs)
00043         {
00044             GlobalExceptionHandler.OnException(ThreadExceptionEventArgs.Exception, string.Empty);
00045         }
00046 
00052         public static void OnException(Exception ex, string additional)
00053         {
00054             System.Windows.Forms.DialogResult res = (new Sylloge.Log.Visual()).Log("Exception: " + System.Environment.NewLine + ex.ToString());
00055             if (GlobalExceptionHandler.UserResultOnException != null) { GlobalExceptionHandler.UserResultOnException(ex, additional, res); }
00056             if (res == System.Windows.Forms.DialogResult.Abort) { System.Windows.Forms.Application.Exit(); }
00057         }
00058 
00064         public static void AppDomain_UnhandledException(System.Object sender, System.UnhandledExceptionEventArgs args)
00065         {
00066             /*This handler does NOT allow the program to stop aborting .. this handler only allows us to do
00067             some sort of clean up or logging before the application goes for a terminal abort. According
00068             to the documentation this handler is supposed to catch both UI (managed) and non-UI (nonmanaged) exceptions
00069             for OUR app domain (not 3rd party extentions)*/
00070             if (args.ExceptionObject != null) {
00071                 Exception e = (Exception)args.ExceptionObject;
00072                 Console.WriteLine("Unhandled Exception called: " + e.Message);
00073                 Sylloge.App.Out(e);
00074             }
00075         }
00076     }
00077 }
 All Classes Namespaces Files Functions Variables Enumerations Properties Events