Global exception capture in winform or wpf

In winform or wpf projects, we will inevitably encounter code blocks that forget to catch exceptions. c ා provides us with a mechanism to catch exceptions globally

Write this in Program.cs in winform

   static class Program
   {      
[STAThread]
static void Main() {
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//UI Thread exception Application.ThreadException += Application_ThreadException; //wrong UI Thread exception AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(
false); Application.Run(new FormMain());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //Log.Error or MessageBox.Show } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { //Log.Error or MessageBox.Show } }

Write like this in App.xaml.cs in wpf

    public partial class App : Application
    {
        public App()
        { 
            //UI thread exception
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            //wrong UI Thread exception
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //Log.Error or MessageBox.Show
        }
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //Log.Error or MessageBox.Show
        }
     }

We can pop up the window prompt or record the log in the exception callback

In this way, most of the exception information can be captured, but some application scenarios are exceptional

For example, when we use [DllImport("xxx.dll")] to call a method written by c\c + +, we can't catch the exception that causes the program to get stuck or flash back

We can try using the [HandleProcessCorruptedStateExceptions] feature

[HandleProcessCorruptedStateExceptions]
public void DoSomething()
{
      try
      {
          Test(1, 2);
      }
      catch(Exception ex)
      {
         //Log or MessageBox.Show
      }
}
[DllImport("xxx.dll")]
public static extern int Test(int a,int b);

Keywords: Windows

Added by ftrudeau on Wed, 22 Apr 2020 18:11:03 +0300