WinForms Global Exception Handling?

后端 未结 7 1310
甜味超标
甜味超标 2020-11-27 05:17

I have implemented a software which have a DLL library which contains a huge set of classes which includes all the methods for my software.

Now i want to be able to

7条回答
  •  暖寄归人
    2020-11-27 05:31

    As an extension of what is shown above, I use the following:

    try
    {
        Application.Run(new FormMain());
    }
    catch (Exception ex)
    {
        RoboReporterConstsAndUtils.HandleException(ex);
    }
    

    ...where the HandleException() method can be something like:

    internal static void HandleException(Exception ex)
    {
        var exDetail = String.Format(ExceptionFormatString,
            ex.Message,
            Environment.NewLine,
            ex.Source,
            ex.StackTrace,
            ex.InnerException);
    
        ExceptionLoggingService.Instance.LogAndEmailExceptionData(string.Format("{0}: {1}: {2}",
            DateTime.Now.ToLongDateString(), GetVersionInfo(), exDetail));
    }
    

    Another way to skin this cat is:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        AppDomain.CurrentDomain.UnhandledException += Unhandled;
        Application.Run(new FormMain());
    }
    
    static void Unhandled(object sender, UnhandledExceptionEventArgs exArgs)
    {
        ExceptionLoggingService.Instance.LogAndEmailMessage(String.Format
            ("From application-wide exception handler: {0}", exArgs.ExceptionObject));
    }
    

    Of course, you can do whatever you want within the Unhandled() method.

提交回复
热议问题