简体   繁体   中英

Handling All Exceptions in a WPF Custom Control Library

When you need handle all exceptions in your WPF application you can use:

Application.DispatcherUnhandledException event

Like explained here and here .

My problem is:

I create a WPF Custom Control Library , so I don't have a app.xaml file. I can't define a Application.DispatcherUnhandlerException.

And even more so, my library will be used to a non .net based app. So I can't define Application.DispatcherUnhandlerException in the main application, because there isn't one.

Is there a way to make this in a dll level?

IMHO you don't want this. Regardless if it's possible or not. You don't want exceptions to die quietly in libs. Clients using your libs should decide what to do with your exceptions. Maybe they want to log it. Send it to a web api. Store it in the db. Whatever. You should only handle specific exceptions in your libs witch your lib could actually deal with. The rest you should bubble up.

I do not think you need an app.xaml to register for those events.

If you do want to do this, add this code in a static initializer in one of your classes that will for sure be used by anyone using the control library:

if (AppDomain.CurrentDomain != null) {
   AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}

if (Dispatcher.CurrentDispatcher != null) {
   Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_UnhandledException;
}

 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
   // Do something with the exception in e.ExceptionObject
 }

 static void CurrentDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
   // Do something with the exception in e.Exception
 }

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