err.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //@File err.go
  2. //@Time 2022/04/26
  3. //@Author #Suyghur,
  4. package result
  5. import "fmt"
  6. /**
  7. 常用通用固定错误
  8. */
  9. const (
  10. Ok int64 = 0
  11. ServerCommonError int64 = 10001
  12. RequestParamError int64 = 10002
  13. TokenExpireError int64 = 10003
  14. TokenParseError int64 = 10004
  15. TokenGenerateError int64 = 10005
  16. DbError int64 = 10006
  17. )
  18. var message map[int64]string
  19. func init() {
  20. message = make(map[int64]string)
  21. message[Ok] = "success"
  22. message[ServerCommonError] = "some unknown error has occurred"
  23. message[RequestParamError] = "request params error"
  24. message[TokenExpireError] = "the token is invalid, please re-authenticate"
  25. message[TokenParseError] = "failed to parse token"
  26. message[TokenGenerateError] = "failed to generate token"
  27. message[DbError] = "database is busy, please try again late"
  28. }
  29. func MapErrMsg(code int64) string {
  30. if msg, ok := message[code]; ok {
  31. return msg
  32. } else {
  33. return "some unknown error has occurred"
  34. }
  35. }
  36. func IsCodeErr(code int64) bool {
  37. if _, ok := message[code]; ok {
  38. return true
  39. } else {
  40. return false
  41. }
  42. }
  43. type CodeError struct {
  44. errCode int64
  45. errMsg string
  46. }
  47. func (e *CodeError) GetErrCode() int64 {
  48. return e.errCode
  49. }
  50. func (e *CodeError) GetErrMsg() string {
  51. return e.errMsg
  52. }
  53. func (e *CodeError) Error() string {
  54. return fmt.Sprintf("code:%d,msg:%s", e.errCode, e.errMsg)
  55. }
  56. func NewErrCodeMsg(code int64, msg string) *CodeError {
  57. return &CodeError{errCode: code, errMsg: msg}
  58. }
  59. func NewErrCode(errCode int64) *CodeError {
  60. return &CodeError{errCode: errCode, errMsg: MapErrMsg(errCode)}
  61. }
  62. func NewErrMsg(errMsg string) *CodeError {
  63. return &CodeError{errCode: ServerCommonError, errMsg: errMsg}
  64. }