errors.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 ExplainCode(code uint32) string {
  25. explain, ok := codeMap[code]
  26. if !ok {
  27. return codeMap[ErrUnknownCode]
  28. }
  29. return explain
  30. }
  31. func TransferFromError(err error) *Error {
  32. transferedErr, ok := err.(*Error)
  33. if ok {
  34. return transferedErr
  35. }
  36. return &Error{
  37. code: ErrUnknownCode,
  38. error: err,
  39. }
  40. }
  41. func NewUnknownError(message string) error {
  42. return newError(ErrUnknownCode, message)
  43. }
  44. func NewParamError(message string) error {
  45. return newError(ErrParamCode, message)
  46. }
  47. func NewConflictError(message string) error {
  48. return newError(ErrConflictCode, message)
  49. }
  50. func NewNotExistError(message string) error {
  51. return newError(ErrNotExistCode, message)
  52. }
  53. func NewTypeTransferError(message string) error {
  54. return newError(ErrTypeTransferCode, message)
  55. }
  56. func NewAuthError(message string) error {
  57. return newError(ErrAuthCode, message)
  58. }
  59. func NewCustomError(message string) error {
  60. return newError(ErrCustomCode, message)
  61. }
  62. type Error struct {
  63. code uint32
  64. error
  65. }
  66. func (err *Error) Code() uint32 {
  67. return err.code
  68. }
  69. func (err *Error) Error() string {
  70. errMsg := fmt.Sprintf("错误代码: 0x%08x\n代码信息: %s\n%+v\n", err.code, codeMap[err.code], err.error)
  71. return errMsg
  72. }
  73. func (err *Error) WithStack() error {
  74. return errors.WithStack(err)
  75. }
  76. func newError(code uint32, message string) *Error {
  77. return &Error{
  78. code: code,
  79. error: errors.New(message),
  80. }
  81. }