errors.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. }
  71. type ConfigurationError struct {
  72. ErrorCode
  73. }
  74. var configurationErrorInstance = ConfigurationError{ErrorCode: 5}
  75. func NewConfigurationError() ConfigurationError {
  76. return configurationErrorInstance
  77. }
  78. func (r ConfigurationError) Error() string {
  79. return r.Prefix() + "Invalid configuration."
  80. }
  81. type InvalidOperationError struct {
  82. ErrorCode
  83. Operation string
  84. }
  85. func NewInvalidOperationError(operation string) InvalidOperationError {
  86. return InvalidOperationError{
  87. ErrorCode: 6,
  88. Operation: operation,
  89. }
  90. }
  91. func (r InvalidOperationError) Error() string {
  92. return r.Prefix() + "Invalid operation: " + r.Operation
  93. }