简体   繁体   中英

Catch all exceptions WPF

In my App.xaml.cs , I have these codes to catch the exceptions and log them

public App()
{
     SetupExceptionHandlingInApp();
     // other codes
}

private void SetupExceptionHandlingInApp()
{
     this.DispatcherUnhandledException += (s, e) =>
     {
        e.Handled = true;
        //LOGGING CODE HERE
        this.Shutdown(-1);
     };
}

[STAThread]
public static void Main()
{
   SetupExceptionHandlingInMain();
   //other codes
}

private static void SetupExceptionHandlingInMain()
{   
    AppDomain.CurrentDomain.UnhandledException += (s, e) =>
    {
        //LOGGING CODE HERE                 
        Environment.Exit(1);
    };           

    System.Windows.Forms.Application.ThreadException += (s, e) =>
    {
        //LOGGING CODE HERE
        Environment.Exit(1);
    };

    TaskScheduler.UnobservedTaskException += (s, e) =>
    {
        //LOGGING CODE HERE
    };
}

Almost cases, I can catch the exception and log it. But the application crashes sometimes while execution, and I can't find an error logged about the exception that caused the crash.

Am I missing a method besides the methods above to catch the exception? I looked at some article on SO but almost them used these methods above.

The log4net works well because I can see all ERROR and INFO log.

EDIT

After following the suggestion of Panagiotis Kanavos, I found out the error:

Application : xxx.exe

Version du Framework : v4.0.30319

Description : le processus a été arrêté en raison d'une erreur interne dans le runtime .NET à l'adresse IP 547541C4 (54380000) avec le code de sortie 80131506.

TRANSLATE

Application: xxx.exe

Framework Version: v4.0.30319

Description: The process was terminated due to an internal error in the .NET Runtime at IP 547541C4 (54380000) with exit code 80131506.

Perhaps you got an exception that corrupted the state of the process? From the documentation :

Starting with the .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

Perhaps you can temporarily specify that your handler is security-critical to be able to catch the exception during debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM