peer_error.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package p2p
  2. import (
  3. "fmt"
  4. )
  5. const (
  6. errInvalidMsgCode = iota
  7. errInvalidMsg
  8. )
  9. var errorToString = map[int]string{
  10. errInvalidMsgCode: "invalid message code",
  11. errInvalidMsg: "invalid message",
  12. }
  13. type peerError struct {
  14. code int
  15. message string
  16. }
  17. func newPeerError(code int, format string, v ...interface{}) *peerError {
  18. desc, ok := errorToString[code]
  19. if !ok {
  20. panic("invalid error code")
  21. }
  22. err := &peerError{code, desc}
  23. if format != "" {
  24. err.message += ": " + fmt.Sprintf(format, v...)
  25. }
  26. return err
  27. }
  28. func (self *peerError) Error() string {
  29. return self.message
  30. }
  31. type DiscReason uint
  32. const (
  33. DiscRequested DiscReason = iota
  34. DiscNetworkError
  35. DiscProtocolError
  36. DiscUselessPeer
  37. DiscTooManyPeers
  38. DiscAlreadyConnected
  39. DiscIncompatibleVersion
  40. DiscInvalidIdentity
  41. DiscQuitting
  42. DiscUnexpectedIdentity
  43. DiscSelf
  44. DiscReadTimeout
  45. DiscSubprotocolError
  46. )
  47. var discReasonToString = [...]string{
  48. DiscRequested: "Disconnect requested",
  49. DiscNetworkError: "Network error",
  50. DiscProtocolError: "Breach of protocol",
  51. DiscUselessPeer: "Useless peer",
  52. DiscTooManyPeers: "Too many peers",
  53. DiscAlreadyConnected: "Already connected",
  54. DiscIncompatibleVersion: "Incompatible P2P protocol version",
  55. DiscInvalidIdentity: "Invalid node identity",
  56. DiscQuitting: "Client quitting",
  57. DiscUnexpectedIdentity: "Unexpected identity",
  58. DiscSelf: "Connected to self",
  59. DiscReadTimeout: "Read timeout",
  60. DiscSubprotocolError: "Subprotocol error",
  61. }
  62. func (d DiscReason) String() string {
  63. if len(discReasonToString) < int(d) {
  64. return fmt.Sprintf("Unknown Reason(%d)", d)
  65. }
  66. return discReasonToString[d]
  67. }
  68. func (d DiscReason) Error() string {
  69. return d.String()
  70. }
  71. func discReasonForError(err error) DiscReason {
  72. if reason, ok := err.(DiscReason); ok {
  73. return reason
  74. }
  75. peerError, ok := err.(*peerError)
  76. if ok {
  77. switch peerError.code {
  78. case errInvalidMsgCode, errInvalidMsg:
  79. return DiscProtocolError
  80. default:
  81. return DiscSubprotocolError
  82. }
  83. }
  84. return DiscSubprotocolError
  85. }