我有一个 LoB WPF 应用程序,需要找到一种方法来处理和记录全局异常。

知道我在做这样的事情:

public partial class App : Application
{
        public App()
        {
           this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
        }

        void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
           string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
           MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
           e.Handled = true;
        }
}

问题是 SimpleIoC “吃掉”了 ViewModel 中抛出的异常。
例子:
public class TestViewModel : ViewModelBase
{
    public TestViewModel()
    {
        throw new Exception("this exception will be catched by SimpleIoC, therefore i'm not able to handle it elsewhere");
    }
}

我正在使用 MVVMLight ViewModelLocator,它看起来像这样:
public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<TestViewModel>();
    }

    public TestViewModelTestViewModel
    {
        get
        {
            return ServiceLocator.Current.GetInstance<TestViewModel>();
        }
    }

    public static void Cleanup()
    {
        SimpleIoc.Default.Unregister<TestViewModel>();
    }
}

根据 this articlethis article 关于异常处理的说法,像这样捕获(并吞下)异常是糟糕的设计,因为它可能会隐藏应用程序中的错误。但我可能会弄错。

最后,这里是我的问题:
如何记录在构建我的 ViewModel 期间发生的异常?

底线:
MVVMLight 真的很棒,我喜欢它!感谢 Laurent Bugnion 和迄今为止为这个项目做出贡献的每一个人。

最佳答案

我记录了这样一个事实,即 SimpleIoc 似乎将构造函数中发生的异常作为 Codeplex 上的一个错误。

您可以在此处查看商品状态:https://mvvmlight.codeplex.com/workitem/7681

更新

我做了一些更多的测试并得出结论,这不是 SimpleIoc 的问题,但实际上是 WPF 如何在绑定(bind)属性中隐藏异常的症状(在这种情况下,ViewModelLocator 类上的绑定(bind)“TestViewModelTestViewModel”属性)。

使用 SimpleIoc 在 WPF View /控件 之外获取 TestViewModel 的实例会导致抛出异常(正如人们所期望的那样)。然后,它会被当时所在的任何处理程序捕获。

另一方面,通过绑定(bind)属性中的 SimpleIoc 获取 TestViewModel 的实例只会导致绑定(bind)失败,但异常似乎并没有“升级”到 WPF 的内部之外。调试时将异常写入输出窗口,但这在测试/生产环境中用处不大。

所以,简而言之,我认为 SimpleIoc 并没有掩盖异常(相反,它是“WPF 的东西”)。

关于c# - WPF 应用程序中的异常日志记录,MVVMLight SimpleIoC 隐藏异常而不是抛出它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21017172/

10-12 00:11
查看更多