NetworkException.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. namespace Vinno.IUS.Common.Network
  5. {
  6. public abstract class NetworkException :Exception
  7. {
  8. public string Name { get; protected set; }
  9. protected NetworkException(string message = "") : base(message)
  10. {
  11. }
  12. /// <summary>
  13. /// Get the network exception by given exception.
  14. /// </summary>
  15. public static Exception Convert(Exception ex)
  16. {
  17. var ioException = ex as IOException;
  18. var socketException = ioException?.InnerException as SocketException;
  19. if (socketException != null)
  20. {
  21. if (socketException.SocketErrorCode == SocketError.NetworkReset ||
  22. socketException.SocketErrorCode == SocketError.ConnectionAborted ||
  23. socketException.SocketErrorCode == SocketError.ConnectionReset)
  24. {
  25. return new ConnectionAbortException();
  26. }
  27. if (socketException.SocketErrorCode == SocketError.NotConnected ||
  28. socketException.SocketErrorCode == SocketError.Shutdown)
  29. {
  30. return new NotConnectedException();
  31. }
  32. if (socketException.SocketErrorCode == SocketError.ConnectionRefused ||
  33. socketException.SocketErrorCode == SocketError.HostDown ||
  34. socketException.SocketErrorCode == SocketError.HostUnreachable)
  35. {
  36. return new CanNotConnectException();
  37. }
  38. if (socketException.SocketErrorCode == SocketError.TimedOut)
  39. {
  40. return new ConnectionTimeoutException();
  41. }
  42. }
  43. return ex;
  44. }
  45. }
  46. /// <summary>
  47. /// The network is aborted exception
  48. /// </summary>
  49. public class ConnectionAbortException : NetworkException
  50. {
  51. public ConnectionAbortException()
  52. {
  53. Name = "ConnectionAbort";
  54. }
  55. }
  56. /// <summary>
  57. /// Network is not connected exception
  58. /// </summary>
  59. public class NotConnectedException :NetworkException
  60. {
  61. public NotConnectedException()
  62. {
  63. Name = "NotConnected";
  64. }
  65. }
  66. /// <summary>
  67. /// Network is not reachable exception.
  68. /// </summary>
  69. public class CanNotConnectException : NetworkException
  70. {
  71. public CanNotConnectException()
  72. {
  73. Name = "CanNotConnect";
  74. }
  75. }
  76. /// <summary>
  77. /// Connect or write or read timeout.
  78. /// </summary>
  79. public class ConnectionTimeoutException : NetworkException
  80. {
  81. public ConnectionTimeoutException()
  82. {
  83. Name = "ConnectionTmeout";
  84. }
  85. }
  86. public class ErrorDataException : NetworkException
  87. {
  88. public ErrorDataException(string message = "")
  89. {
  90. Name = "ErrorData";
  91. }
  92. }
  93. }