Wednesday 7 October 2009

Silverlight 3 – handling exceptions in page views

This post has moved to http://www.scottleckie.com/2009/10/silverlight-3-%e2%80%93-handling-exceptions-in-page-views/

How do you handle the situation where your new Silverlight page needs to shout a warning or error, and then die? No idea, but this is how I do it…
Originally, I was quite scared of my Silverlight pages throwing an exception and then I realised that this was just another object and if we throw an exception, hopefully let the user know, and bail out, then that’s fine.
So the pattern I am now working with is this;
  1. Constructor – set up the load operations
  2. Page_Loaded events – bind the XAML objects to the retrieved data
    • On any error; display a meaningful message, in a semi-modal window
    • Navigate back to a safe place (e.g. /home)
What do I mean by “semi-modal”? Well, from the user’s perspective, it should be modal; display a message then abort. Silverlight, however, can’t display a truly modal message so we need to take account of that in exception handling… (more of which in a mo…)
So, step one, is to define a rather apt method called “ScreamAndExit()” which looks like this;
protected void ScreamAndExit(string msg)
{
ChildWindow err = new ErrorWindow("Could not load the requested machine list", msg);
err.Show();
NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
}


Note that ErrorWindow is defined in the Silverlight 3.0 Navigation Framework.


How do we call this? (Relatively) easy;


// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
activityDisplay.IsActive = true;
int id = -1;
string searchType = "";
try
{
switch (searchType.ToLower())
{
// Magic
default: ScreamAndExit("Invalid request type");
return;
}
}
catch (Exception ex)
{
activityDisplay.IsActive = false;
ScreamAndExit(ex.Message);
return;
}
}


And that’s almost it. The “almost” refers to the “semi-modal” discussion; Silverlight windows display asynchronously and so if you simply call “ScreamAndExit” and carry on, then the rest of the code will be executed. Make sure you call ScreamAndExit and the return from each call…

No comments:

Post a Comment