errors.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package fserr
  2. import (
  3. "fmt"
  4. "github.com/pkg/errors"
  5. )
  6. const (
  7. ErrUnknownCode uint32 = 0x00000001
  8. ErrParamCode uint32 = 0x00000002
  9. ErrConflictCode uint32 = 0x00000003
  10. ErrNotExistCode uint32 = 0x00000004
  11. ErrTypeTransferCode uint32 = 0x00000005
  12. ErrAuthCode uint32 = 0x00000006
  13. ErrCustomCode uint32 = 0x00001000
  14. )
  15. var codeMap = map[uint32]string{
  16. ErrUnknownCode: "未知错误",
  17. ErrParamCode: "参数错误",
  18. ErrConflictCode: "资源冲突",
  19. ErrNotExistCode: "资源不存在",
  20. ErrTypeTransferCode: "类型转换错误",
  21. ErrAuthCode: "鉴权错误",
  22. ErrCustomCode: "自定义错误",
  23. }
  24. func NewFromError(err error) error {
  25. _, ok := err.(*Error)
  26. if ok {
  27. return err
  28. }
  29. return NewUnknownError(err.Error())
  30. }
  31. func NewUnknownError(message string) error {
  32. return newError(ErrUnknownCode, message)
  33. }
  34. func NewParamError(message string) error {
  35. return newError(ErrParamCode, message)
  36. }
  37. func NewConflictError(message string) error {
  38. return newError(ErrConflictCode, message)
  39. }
  40. func NewNotExistError(message string) error {
  41. return newError(ErrNotExistCode, message)
  42. }
  43. func NewTypeTransferError(message string) error {
  44. return newError(ErrTypeTransferCode, message)
  45. }
  46. func NewAuthError(message string) error {
  47. return newError(ErrAuthCode, message)
  48. }
  49. func NewCustomError(message string) error {
  50. return newError(ErrCustomCode, message)
  51. }
  52. type Error struct {
  53. code uint32
  54. error
  55. }
  56. func (err Error) Error() string {
  57. errMsg := fmt.Sprintf("错误代码: 0x%08x\n代码信息: %s\n%+v\n", err.code, codeMap[err.code], err.error)
  58. return errMsg
  59. }
  60. func newError(code uint32, message string) *Error {
  61. return &Error{
  62. code: code,
  63. error: errors.New(message),
  64. }
  65. }