github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/p2p/peer_error.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:41</date> 10 //</624450105629478912> 11 12 13 package p2p 14 15 import ( 16 "errors" 17 "fmt" 18 ) 19 20 const ( 21 errInvalidMsgCode = iota 22 errInvalidMsg 23 ) 24 25 var errorToString = map[int]string{ 26 errInvalidMsgCode: "invalid message code", 27 errInvalidMsg: "invalid message", 28 } 29 30 type peerError struct { 31 code int 32 message string 33 } 34 35 func newPeerError(code int, format string, v ...interface{}) *peerError { 36 desc, ok := errorToString[code] 37 if !ok { 38 panic("invalid error code") 39 } 40 err := &peerError{code, desc} 41 if format != "" { 42 err.message += ": " + fmt.Sprintf(format, v...) 43 } 44 return err 45 } 46 47 func (pe *peerError) Error() string { 48 return pe.message 49 } 50 51 var errProtocolReturned = errors.New("protocol returned") 52 53 type DiscReason uint 54 55 const ( 56 DiscRequested DiscReason = iota 57 DiscNetworkError 58 DiscProtocolError 59 DiscUselessPeer 60 DiscTooManyPeers 61 DiscAlreadyConnected 62 DiscIncompatibleVersion 63 DiscInvalidIdentity 64 DiscQuitting 65 DiscUnexpectedIdentity 66 DiscSelf 67 DiscReadTimeout 68 DiscSubprotocolError = 0x10 69 ) 70 71 var discReasonToString = [...]string{ 72 DiscRequested: "disconnect requested", 73 DiscNetworkError: "network error", 74 DiscProtocolError: "breach of protocol", 75 DiscUselessPeer: "useless peer", 76 DiscTooManyPeers: "too many peers", 77 DiscAlreadyConnected: "already connected", 78 DiscIncompatibleVersion: "incompatible p2p protocol version", 79 DiscInvalidIdentity: "invalid node identity", 80 DiscQuitting: "client quitting", 81 DiscUnexpectedIdentity: "unexpected identity", 82 DiscSelf: "connected to self", 83 DiscReadTimeout: "read timeout", 84 DiscSubprotocolError: "subprotocol error", 85 } 86 87 func (d DiscReason) String() string { 88 if len(discReasonToString) < int(d) { 89 return fmt.Sprintf("unknown disconnect reason %d", d) 90 } 91 return discReasonToString[d] 92 } 93 94 func (d DiscReason) Error() string { 95 return d.String() 96 } 97 98 func discReasonForError(err error) DiscReason { 99 if reason, ok := err.(DiscReason); ok { 100 return reason 101 } 102 if err == errProtocolReturned { 103 return DiscQuitting 104 } 105 peerError, ok := err.(*peerError) 106 if ok { 107 switch peerError.code { 108 case errInvalidMsgCode, errInvalidMsg: 109 return DiscProtocolError 110 default: 111 return DiscSubprotocolError 112 } 113 } 114 return DiscSubprotocolError 115 } 116