error.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package util
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  6. )
  7. // CommonError 微信返回的通用错误json
  8. type CommonError struct {
  9. ErrCode int64 `json:"errcode"`
  10. ErrMsg string `json:"errmsg"`
  11. }
  12. // DecodeWithCommonError 将返回值按照CommonError解析
  13. func DecodeWithCommonError(response []byte, apiName string) (err error) {
  14. var commError CommonError
  15. err = json.Unmarshal(response, &commError)
  16. if err != nil {
  17. return
  18. }
  19. if commError.ErrCode != 0 {
  20. return fmt.Errorf("%s Error , errcode=%d , errmsg=%s", apiName, commError.ErrCode, commError.ErrMsg)
  21. }
  22. return nil
  23. }
  24. // DecodeWithError 将返回值按照解析
  25. func DecodeWithError(response []byte, obj interface{}, apiName string) error {
  26. err := json.Unmarshal(response, obj)
  27. if err != nil {
  28. return fmt.Errorf("json Unmarshal Error, err=%v", err)
  29. }
  30. responseObj := reflect.ValueOf(obj)
  31. if !responseObj.IsValid() {
  32. return fmt.Errorf("obj is invalid")
  33. }
  34. commonError := responseObj.Elem().FieldByName("CommonError")
  35. if !commonError.IsValid() || commonError.Kind() != reflect.Struct {
  36. return fmt.Errorf("commonError is invalid or not struct")
  37. }
  38. errCode := commonError.FieldByName("ErrCode")
  39. errMsg := commonError.FieldByName("ErrMsg")
  40. if !errCode.IsValid() || !errMsg.IsValid() {
  41. return fmt.Errorf("errcode or errmsg is invalid")
  42. }
  43. if errCode.Int() != 0 {
  44. return fmt.Errorf("%s Error , errcode=%d , errmsg=%s", apiName, errCode.Int(), errMsg.String())
  45. }
  46. return nil
  47. }