Managing Errors in a Windows Phone Silverlight Application

This example shows how to create an error page in your Windows Phone Silverlight application that displays whenever your app encounters an unhandled exception. 
  1. Add a new page to your application, for example ErrorPage.xaml.

  2. Modify ErrorPage.xaml to have a text block (named ErrorText) that will be used to display the error. For example, modify the default ContentPanel:

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1">
         <Border BorderBrush="White">

             <TextBlock x:Name="ErrorText" Style="{StaticResource PhoneTextSmallStyle}"  
                        TextWrapping="Wrap" />
         </Border>
    </Grid>

  3. Edit the ErrorPage class (ErrorPage.xaml.cs) to include the following code. This code sets up an Exception object that is linked to the ErrorText.text field.

    public partial class ErrorPage : PhoneApplicationPage
    {
      public ErrorPage()
      {
        InitializeComponent();
      }
    
      public static Exception Exception;
    
      // Executes when the user navigates to this page
      protected override void OnNavigatedTo(NavigationEventArgs e)
      {
        ErrorText.Text = Exception.ToString();
      }
    }

  4. Next, create the event handler to navigate to the error page and display the error message whenever you encounter an unhandled exception.
    In the App.xaml.cs file, find the existing Application_UnhandledException event handler and replace it with the following:

    // Code to execute on Unhandled Exceptions
    private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
       if (System.Diagnostics.Debugger.IsAttached)
       {
           // An unhandled exception has occurred; break in the debugger

           System.Diagnostics.Debugger.Break();
       }

       e.Handled = true;
       ErrorPage.Exception = e.ExceptionObject;
      (RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =
            new Uri("/ErrorPage.xaml", UriKind.Relative);
    }

    Note: Setting the Source property to a value that is different from the displayed content causes the frame to navigate to the new content. 

This setup is very useful for debugging an application. But, it doesn't replace the need to handle exceptions in your code.

References:

Comments

Contact us