errors.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package fserr
  2. import (
  3. "errors"
  4. "fmt"
  5. pkgerrors "github.com/pkg/errors"
  6. )
  7. const (
  8. ErrUnknownCode uint32 = 0x00000001
  9. ErrParamCode uint32 = 0x00000002
  10. ErrConflictCode uint32 = 0x00000003
  11. ErrNotExistCode uint32 = 0x00000004
  12. ErrTypeTransferCode uint32 = 0x00000005
  13. ErrAuthCode uint32 = 0x00000006
  14. ErrCustomCode uint32 = 0x00001000
  15. )
  16. var codeMap = map[uint32]string{
  17. ErrUnknownCode: "未知错误",
  18. ErrParamCode: "参数错误",
  19. ErrConflictCode: "资源冲突",
  20. ErrNotExistCode: "资源不存在",
  21. ErrTypeTransferCode: "类型转换错误",
  22. ErrAuthCode: "鉴权错误",
  23. ErrCustomCode: "自定义错误",
  24. }
  25. func ExplainCode(code uint32) string {
  26. explain, ok := codeMap[code]
  27. if !ok {
  28. return codeMap[ErrUnknownCode]
  29. }
  30. return explain
  31. }
  32. func TransferFromError(err error) *Error {
  33. transferErr, ok := err.(*Error)
  34. if ok {
  35. return transferErr
  36. }
  37. return &Error{
  38. code: ErrUnknownCode,
  39. error: err,
  40. }
  41. }
  42. func NewUnknownError(message string) *Error {
  43. return newError(ErrUnknownCode, message)
  44. }
  45. func NewParamError(message string) *Error {
  46. return newError(ErrParamCode, message)
  47. }
  48. func NewConflictError(message string) *Error {
  49. return newError(ErrConflictCode, message)
  50. }
  51. func NewNotExistError(message string) *Error {
  52. return newError(ErrNotExistCode, message)
  53. }
  54. func NewTypeTransferError(message string) *Error {
  55. return newError(ErrTypeTransferCode, message)
  56. }
  57. func NewAuthError(message string) *Error {
  58. return newError(ErrAuthCode, message)
  59. }
  60. func NewCustomError(message string) *Error {
  61. return newError(ErrCustomCode, message)
  62. }
  63. type Error struct {
  64. code uint32
  65. message string
  66. error
  67. }
  68. func (err *Error) Code() uint32 {
  69. return err.code
  70. }
  71. func (err *Error) Error() string {
  72. errMsg := fmt.Sprintf("\n错误代码: 0x%08x\n代码信息: %s\n%+v\n", err.code, codeMap[err.code], err.error)
  73. return errMsg
  74. }
  75. func (err *Error) WithStack() error {
  76. return &Error{
  77. code: err.code,
  78. message: err.message,
  79. error: pkgerrors.New(err.message),
  80. }
  81. }
  82. func (err *Error) Is(target error) bool {
  83. transferErr, ok := target.(*Error)
  84. if !ok {
  85. return false
  86. }
  87. return err.message == transferErr.message && err.code == transferErr.code
  88. }
  89. func newError(code uint32, message string) *Error {
  90. return &Error{
  91. code: code,
  92. message: message,
  93. error: errors.New(message),
  94. }
  95. }