error.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package util
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  6. )
  7. // CommonError 微信返回的通用错误 json
  8. type CommonError struct {
  9. apiName string
  10. ErrCode int64 `json:"errcode"`
  11. ErrMsg string `json:"errmsg"`
  12. }
  13. func (c *CommonError) Error() string {
  14. return fmt.Sprintf("%s Error , errcode=%d , errmsg=%s", c.apiName, c.ErrCode, c.ErrMsg)
  15. }
  16. // NewCommonError 新建 CommonError 错误,对于无 errcode 和 errmsg 的返回也可以返回该通用错误
  17. func NewCommonError(apiName string, code int64, msg string) *CommonError {
  18. return &CommonError{
  19. apiName: apiName,
  20. ErrCode: code,
  21. ErrMsg: msg,
  22. }
  23. }
  24. // DecodeWithCommonError 将返回值按照 CommonError 解析
  25. func DecodeWithCommonError(response []byte, apiName string) (err error) {
  26. var commError CommonError
  27. err = json.Unmarshal(response, &commError)
  28. if err != nil {
  29. return
  30. }
  31. commError.apiName = apiName
  32. if commError.ErrCode != 0 {
  33. return &commError
  34. }
  35. return nil
  36. }
  37. // DecodeWithError 将返回值按照解析
  38. func DecodeWithError(response []byte, obj interface{}, apiName string) error {
  39. err := json.Unmarshal(response, obj)
  40. if err != nil {
  41. return fmt.Errorf("json Unmarshal Error, err=%v", err)
  42. }
  43. responseObj := reflect.ValueOf(obj)
  44. if !responseObj.IsValid() {
  45. return fmt.Errorf("obj is invalid")
  46. }
  47. commonError := responseObj.Elem().FieldByName("CommonError")
  48. if !commonError.IsValid() || commonError.Kind() != reflect.Struct {
  49. return fmt.Errorf("commonError is invalid or not struct")
  50. }
  51. errCode := commonError.FieldByName("ErrCode")
  52. errMsg := commonError.FieldByName("ErrMsg")
  53. if !errCode.IsValid() || !errMsg.IsValid() {
  54. return fmt.Errorf("errcode or errmsg is invalid")
  55. }
  56. if errCode.Int() != 0 {
  57. return &CommonError{
  58. apiName: apiName,
  59. ErrCode: errCode.Int(),
  60. ErrMsg: errMsg.String(),
  61. }
  62. }
  63. return nil
  64. }