ExceptionHelper.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows.Forms;
  6. namespace Core.Mes.Client.Comm.Tool
  7. {
  8. public class ExceptionHelper
  9. {
  10. private static int _registCnt = 0;
  11. /// <summary>
  12. /// 注册未捕获的异常。如果出现未捕获的异常,则自动捕获并写入到本地日志文件中。
  13. /// </summary>
  14. public static void RegistException()
  15. {
  16. if (_registCnt > 0) return;
  17. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
  18. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  19. _registCnt++;
  20. }
  21. private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
  22. {
  23. LogHelper.WriteLogs("Application_ThreadException", GetExceptionMsg(e.Exception));
  24. }
  25. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  26. {
  27. LogHelper.WriteLogs("CurrentDomain_UnhandledException", GetExceptionMsg(e.ExceptionObject as Exception));
  28. }
  29. private static string GetExceptionMsg(Exception e)
  30. {
  31. if (e == null) return "";
  32. string msg = "错误消息:" + e.Message;
  33. msg += "\r\n错误源:" + e.Source;
  34. msg += "\r\n详细信息:" + e.StackTrace;
  35. return msg;
  36. }
  37. }
  38. }