Home > Software engineering >  Global error handling doesn't work in WPF
Global error handling doesn't work in WPF

Time:01-25

I want to handle all unexpected errors in a WPF application. When I look at, there are different events for different situation to capture and control error. Also I added these in application constructor method

public App()
{
    AppDomain.CurrentDomain.FirstChanceException  = OnFirstChanceException;
    AppDomain.CurrentDomain.UnhandledException  = OnUnhandledException;
    Dispatcher.UnhandledException  = OnDispatcherUnhandledException;
    TaskScheduler.UnobservedTaskException  = OnUnobservedTaskException;
}

However, I try that for checking handling but they didn't work. What is the reason?

private void btnStart_Click(object sender, RoutedEventArgs e) //2021112242
{
    throw new StackOverflowException();
}

CodePudding user response:

App has an event for this called DispatcherUnhandledException. This works in most cases but when the exception is thrown from a separate thread it gets a little hairy.

public partial class App
{
    public App()
    {
        // Globally handle errors/exceptions for a friendly close.
        DispatcherUnhandledException  = DispatcherOnUnhandledException;
    }

    private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        try
        {
            e.Handled = true;
            e.Exception.Display("An unhandled exception occurred, the application will now close.");
            e.Exception.Log(); // log the problem.

            Shutdown(-1); // assume not recoverable.
        }
        catch
        {
            Shutdown(-1);
        }
    }
}

CodePudding user response:

Every exception event has his own callback method & event object

// Dispatcher.UnhandledException
     private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
            {

            }
// TaskScheduler.UnobservedTaskException
            private static void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
            {

            }
//  AppDomain.CurrentDomain.UnhandledException    
            private static void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
            {

            }

// AppDomain.CurrentDomain.FirstChanceException
    private static void OnCurrentDomainUnhandledException(object sender, FirstChanceExceptionEventArgs e)
                {

                }
  •  Tags:  
  • Related