【问题标题】:Handling All Exceptions in a WPF Custom Control Library处理 WPF 自定义控件库中的所有异常
【发布时间】:2016-08-19 05:34:23
【问题描述】:

当您需要处理 WPF 应用程序中的所有异常时,您可以使用:

Application.DispatcherUnhandledException事件

就像here 和here 解释的那样。

我的问题是:

我创建了一个 WPF 自定义控件库,所以我没有 app.xaml 文件。我无法定义 Application.DispatcherUnhandlerException。

更重要的是,我的库将用于非基于 .net 的应用程序。所以我不能在主应用程序中定义Application.DispatcherUnhandlerException,因为没有。

有没有办法在 dll 级别进行此操作?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    恕我直言,你不想要这个。不管它是否可能。您不希望异常在库中安静地死去。使用您的库的客户应决定如何处理您的异常。也许他们想记录它。将其发送到 Web api。将其存储在数据库中。任何。您应该只处理您的库中的特定异常,因为您的库实际上可以处理。其余的你应该冒泡。

    【讨论】:

    • 我同意你的观点,不好杀死库内的异常。但我对杀死异常不感兴趣。我对处理它们很感兴趣,可以处理异常,即使这样让它继续被抛出。另一点是,我没有分发我的库,我将它用于非常特定的目的。该库将成为系统的一部分,但系统不在 .net 中。所以我需要将异常日志放在我的库中。
    【解决方案2】:

    我认为您不需要 app.xaml 来注册这些事件。

    如果您确实想这样做,请将此代码添加到您的某个类中的静态初始化程序中,任何使用控件库的人肯定会使用该类:

    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
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 2019-02-06
      • 2012-02-03
      • 2011-10-13
      • 1970-01-01
      相关资源
      最近更新 更多