Tuesday, July 10, 2012

Handling Errors in Windows Phone

When I published my first phone application, Basic Jacks or Better Video Poker, I put little to no error handling within my app because I never encountered any while testing it.  I probably logged over 50+ hours of playing it and never encountered any crashes.  But on the Microsoft App Hub site, it shows my app is crashing 1-2 times a week:


The stack trace pointed to the AdControl which points me in the direction of that this is a Microsoft problem and not related to my source code. 

Here is a breakdown on adding a catch all error handling to your windows phone app using C#.
  1. First create a ErrorPage.xaml page to your project.
  2. Add a Textblock control "ErrorText" that will store your error message:

    <TextBlock x:Name="ErrorText" Style="{StaticResource PhoneTextSmallStyle}" TextWrapping="Wrap" Text="error will go here" Margin="12,20,12,0" />

  3. Modify the Header field and add any other elements to the page to make it user friendly:
  4. Now open the code behind page (ErrorPage.xaml.cs) and add the following code:

           public static Exception Exception;

            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                ErrorText.Text = Exception.Message;
            }

  5. Next add code to the App.xaml.cs file in the Application_UnhandledException procedure:

                e.Handled = true;

                ErrorPage.Exception = e.ExceptionObject;

                (RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =              new Uri("/ErrorPage.xaml", UriKind.Relative);

  6. Add the same code to the RootFrame_NavigationFailed procedure using the e.Exception object instead of e.ExceptionObject:

                e.Handled = true;

                ErrorPage.Exception = e.Exception;

                (RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =              new Uri("/ErrorPage.xaml"UriKind.Relative);

  7. Next add a button and code that you know will fail. Like divide by 0 or navigate to a page that does not exists.
Just some footnotes. 
  • I added the Report Error button that will send the Stack Trace back to me.  Its probably not needed because the Stack Trace is appearing in the reports.  
  • The Back button will navigate the user back to the start page. The reason why to manually pushed the user is because the Back button the phone is what is causing the AdControl error.  This gives a user the ability to stay in the app otherwise they would have to click the Window button then reopen the application.

No comments:

Post a Comment