Program.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Windows.Forms;
  6. namespace HttpServer
  7. {
  8. static class Program
  9. {
  10. /// <summary>
  11. /// 应用程序的主入口点。
  12. /// </summary>
  13. [STAThread]
  14. static void Main()
  15. {
  16. // 设置未处理异常的处理程序
  17. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  18. TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  19. // 设置应用程序捕获未处理的异常
  20. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  21. Application.EnableVisualStyles();
  22. Application.SetCompatibleTextRenderingDefault(false);
  23. Application.Run(new Form1());
  24. }
  25. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  26. {
  27. LogException(e.ExceptionObject as Exception);
  28. }
  29. private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
  30. {
  31. // LogException(e.Exception);
  32. // 在生产环境中,可以选择立即抛出异常以终止程序,或者在调试时使用以下代码
  33. e.SetObserved();
  34. }
  35. private static void LogException(Exception ex)
  36. {
  37. string errorLog = $"Unhandled Exception occurred: {ex.Message}, Stack Trace: {ex.StackTrace}";
  38. try
  39. {
  40. //File.AppendAllText("error.log", errorLog);
  41. }
  42. catch
  43. {
  44. // 如果写入日志失败,可以考虑其他的错误处理方式
  45. }
  46. }
  47. }
  48. }