Catching Uncaught Exceptions

Wpf Example

Modify App.xaml.cs to be like this:

using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using NetExceptionReporter;

namespace WpfApplicationTest
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        static ExceptionReporter _reporter = new ExceptionReporter();
        internal static ExceptionReporter Reporter
        {
            get { return _reporter; }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            #region Catch uncaught exceptions with exception reporter

            if (!Debugger.IsAttached)
            {
                Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler((_s, _e) =>
                {
                    _e.Handled = true;

                    _reporter.ReportException(_e.Exception);
                });
            }

            #endregion

            base.OnStartup(e);
        }
    }
}

WindowsForms Example

Modify Program.cs to be like this:

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using NetExceptionReporter;

namespace WindowsFormsTest
{
    static class Program
    {
        static ExceptionReporter _reporter = new ExceptionReporter();
        internal static ExceptionReporter Reporter
        {
            get { return _reporter; }
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            #region Catch uncaught exceptions with exception reporter

            if (!Debugger.IsAttached)
            {
                // Add the event handler for handling UI thread exceptions to the event.
                Application.ThreadException += new ThreadExceptionEventHandler((s, e) =>
                {
                    _reporter.ReportException(e.Exception);
                });

                // Add the event handler for handling non-UI thread exceptions to the event. 
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((s, e) =>
                {
                    _reporter.ReportException((Exception)e.ExceptionObject, e.IsTerminating);
                });

                // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            }

            #endregion

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Last edited Oct 4, 2012 at 10:08 PM by jah4, version 9

Comments

No comments yet.