简体   繁体   中英

Attaching two different Exception Handlers to program?

In my application, I am using the free NBug crash reporting library. In order to integrate it into your project you need to add these two lines in your Program.cs:

AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException;
Application.ThreadException += NBug.Handler.ThreadException;

However, I need to run a block of code in cases where my program crashes. This code needs to clean up some entries in a mysql database. I thought of simply adding extra event handles after the NBug ones:

AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException;
Application.ThreadException += NBug.Handler.ThreadException;
Application.ThreadException += new ThreadExceptionEventHandler(mysqlcleanup);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(mysqlcleanup1);

However in this case the program only performs the mysql cleanup events, and ignores the NBug ones. Is it even possible to have multiple exception handlers? I thought of editing the NBug source to run the mysql commands but that would mean attaching the mysql library to that project which is less than ideal.

Any ideas are very welcome.

You can try to hook the AppDomain exceptions only to your event handlers. Create then 2 of your own exception events, same signature as the Appdomain's. Hook the NBug to your own events. In your event handlers, do your mysql cleanup and then raise your your own events which should notify NBug. Don't know if this workaround will work...

I will just illustrate one event:

create the following event:

public event UnhandledExceptionEventHandler OnUnhandledException;

Remove the NBug assignments from the Appdomain exceptions, keeping only your own assigned. There you assign the NBug method to your new event, something like this:

OnUnhandledException += Nbug..... 

like you had it assigned to the Appdomains event. Then in your method where you cleanup mysql you implement:

OnUnhandledException(sender, unhandledExceptionEventArgs);

Hope this helps. Note that it is good practise to check first if your event is assigned or not before calling it:

if (OnUnhandledException != null)
OnUnhandledException(sender, unhandledExceptionEventArgs);

but in your case you know it is assigned to NBug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM