开发者

Where do I catch Exceptions in MVVM?

My view model class has a method (not sure if that is good practice or if view models are supposed to be strictly property and property changing mechanisms) that connects to a service. Of course I want to handle any possible WCF exceptions when connecting or disconnecting.

Let's use endpoint not found as an example considering that is an exception that I would want to bring to the user's attention. Consider the rough code example:

public void Connect()
{
    ServiceClient proxy = null;
    try
    {
        proxy = new ServiceClient();
        proxy.Subscribe();
        // ...
    }
    catch(EndpointNotFound开发者_StackOverflow中文版Exception)
    {
        // should I do something here?
    }
    // .. other WCF related exception catches and a finally
}

Is it considered good practice to maybe invoke System.Windows.MessageBox.Show() directly within the catch or should I maybe rethrow the exception so another layer of my WPF application catches it? If so, where is the ideal place to catch such an exception?


I've been handling exceptions in my MVVM client by catching them and wrapping them in an ErrorViewModel property of whatever ViewModel caught the exception.

Let's say a ViewModel A catches the EndpointNotFoundException. To present this error, I wrap the Exception in an ErrorViewModel and assign that to A's Error property.

The View associated with A contains a ContentControl bound to A's Error property. Meanwhile, I use a DataTemplate to associate an Error View to the ErrorViewModel. In that View, Visibility is determined by whether or not A's Error property contains an exception.

So A's View contains an error-message View that will only appear when an exception is caught, and can be dismissed by the user (an OK button on the error-message View invokes a command on A that clears A's Error property, thereby changing the error-message View's visibility to Collapsed).

Thus far, this seems to be a good approach that preserves proper MVVM decoupling.

Hope that helps. One way or another, honestly, I'd consider System.Windows.MessageBox.Show() in a WPF app as purely a last resort. Why give up rich control over the UI in favor of that old thing? Speaking of which, here's another popup-implementation approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜