在处理视图模型致命异常/型号视图、模型、型号、异常

2023-09-04 02:06:31 作者:由于不幸i

我必须使用MV-VM的方式编写的应用程序。

I have an application written using the M-V-VM approach.

的数据访问中的模型进行。如果在这里出现致命错误(例如,连接到数据源丢失),并且抛出异常。此异常泡到视图模型。

The data access is done in the Model. If a fatal error occurs here (for example, the connection to the data source is lost), and Exception is thrown. This Exception bubbles up to the ViewModel.

然而,由于数据访问原来的触发器是数据绑定,WPF吞下这个异常(它只是记录的时候,应用程序是在调试器下运行的输出窗口)。

However, because the original trigger of the data access was a data binding, WPF swallows this exception (it is only logged in the output window when the app is run under the debugger).

我宁愿这个异常仍未处理,所以我的应用程序范围内未处理的异常处理程序可以把它捡起来,记录它,并优雅地退出。我怎样才能做到这一点?

I'd rather this exception remained unhandled so my application-wide unhandled exception handler could pick it up, log it and gracefully exit. How can I achieve this?

推荐答案

您可以在队列调度异常抛出的动作。

You could queue an exception-throwing action on the dispatcher.

    // This property is connected to the window using databinding
    public string ExceptionThrowingBoundedField
    {
        get
        {

            try
            {
                // This function might throw an exception
                return GetValueFromDatabase();               
            }
            catch (Exception ex)
            {
                ApplicationException exWrapper = new ApplicationException("Wrapped Exception",
                                                                          ex);
                Action throwException = () => { throw exWrapper; };
                Dispatcher.CurrentDispatcher.BeginInvoke(throwException);
                return "";
            }
        }
    }