errors.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package errors
  2. import (
  3. "fmt"
  4. )
  5. func HasCode(err error, code int) bool {
  6. if errWithCode, ok := err.(ErrorWithCode); ok {
  7. return errWithCode.Code() == code
  8. }
  9. return false
  10. }
  11. type ErrorWithCode interface {
  12. error
  13. Code() int
  14. }
  15. type ErrorCode int
  16. func (code ErrorCode) Code() int {
  17. return int(code)
  18. }
  19. func (code ErrorCode) Prefix() string {
  20. return fmt.Sprintf("[Error 0x%04X] ", code.Code())
  21. }
  22. type AuthenticationError struct {
  23. ErrorCode
  24. AuthDetail interface{}
  25. }
  26. func NewAuthenticationError(detail interface{}) AuthenticationError {
  27. return AuthenticationError{
  28. ErrorCode: 1,
  29. AuthDetail: detail,
  30. }
  31. }
  32. func (err AuthenticationError) Error() string {
  33. return fmt.Sprintf("%sInvalid auth %v", err.Prefix(), err.AuthDetail)
  34. }
  35. type ProtocolVersionError struct {
  36. ErrorCode
  37. Version int
  38. }
  39. func NewProtocolVersionError(version int) ProtocolVersionError {
  40. return ProtocolVersionError{
  41. ErrorCode: 2,
  42. Version: version,
  43. }
  44. }
  45. func (err ProtocolVersionError) Error() string {
  46. return fmt.Sprintf("%sInvalid version %d", err.Prefix(), err.Version)
  47. }
  48. type CorruptedPacketError struct {
  49. ErrorCode
  50. }
  51. var corruptedPacketErrorInstance = CorruptedPacketError{ErrorCode: 3}
  52. func NewCorruptedPacketError() CorruptedPacketError {
  53. return corruptedPacketErrorInstance
  54. }
  55. func (err CorruptedPacketError) Error() string {
  56. return err.Prefix() + "Corrupted packet."
  57. }
  58. type IPFormatError struct {
  59. ErrorCode
  60. IP []byte
  61. }
  62. func NewIPFormatError(ip []byte) IPFormatError {
  63. return IPFormatError{
  64. ErrorCode: 4,
  65. IP: ip,
  66. }
  67. }
  68. func (err IPFormatError) Error() string {
  69. return fmt.Sprintf("%sInvalid IP %v", err.Prefix(), err.IP)
  70. }