Handling fatal exceptions in ViewModel/Model

爷,独闯天下 提交于 2019-12-21 03:36:18

问题


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.

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?


回答1:


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 "";
            }
        }
    }



回答2:


Recently come across a way of getting around the swallowed exception problem in a global way.

Create a custom binding class and override UpdateSourceExceptionFilter - see sample in this thread.

Unfortunately this is just WPF 4.0 and not SL 4.0.



来源:https://stackoverflow.com/questions/2353610/handling-fatal-exceptions-in-viewmodel-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!