CustomExceptionHandler.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Collections;
  7. using System.Windows.Forms;
  8. using System.Threading;
  9. namespace HXX.Scanner.Common
  10. {
  11. public class CustomExceptionHandlerForClient
  12. {
  13. public CustomExceptionHandlerForClient()
  14. {
  15. //处理未捕获的异常
  16. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  17. //处理UI线程异常
  18. Application.ThreadException += new ThreadExceptionEventHandler(this.OnThreadExceptionUI);
  19. //处理非UI线程异常
  20. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.OnThreadExceptionUnhandled);
  21. }
  22. private void OnThreadExceptionUI(object sender, ThreadExceptionEventArgs args)
  23. {
  24. try
  25. {
  26. LogManager.WriteLog(args.Exception);
  27. //MsgManager.Error(args.Exception.Message);
  28. }
  29. catch (Exception ee)
  30. {
  31. LogManager.WriteLog(ee);
  32. //MsgManager.Error(ee.Message);
  33. }
  34. }
  35. private void OnThreadExceptionUnhandled(object sender, UnhandledExceptionEventArgs args)
  36. {
  37. try
  38. {
  39. Exception ee = args.ExceptionObject as Exception;
  40. LogManager.WriteLog(ee);
  41. //MsgManager.Error(ee.Message);
  42. }
  43. catch (Exception eee)
  44. {
  45. LogManager.WriteLog(eee);
  46. //MsgManager.Error(eee.Message);
  47. }
  48. }
  49. }
  50. public class CustomExceptionHandlerForServer
  51. {
  52. public CustomExceptionHandlerForServer()
  53. {
  54. Application.ThreadException += new ThreadExceptionEventHandler(this.OnThreadException);
  55. }
  56. private void OnThreadException(object sender, ThreadExceptionEventArgs args)
  57. {
  58. try
  59. {
  60. LogManager.WriteLog(args.Exception.Message);
  61. }
  62. catch (Exception ee)
  63. {
  64. LogManager.WriteLog(ee);
  65. LogManager.WriteLog(ee.Message);
  66. }
  67. }
  68. }
  69. }