error.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // DecodeWithCommonError 将返回值按照CommonError解析
  17. func DecodeWithCommonError(response []byte, apiName string) (err error) {
  18. var commError CommonError
  19. err = json.Unmarshal(response, &commError)
  20. if err != nil {
  21. return
  22. }
  23. commError.apiName = apiName
  24. if commError.ErrCode != 0 {
  25. return &commError
  26. }
  27. return nil
  28. }
  29. // DecodeWithError 将返回值按照解析
  30. func DecodeWithError(response []byte, obj interface{}, apiName string) error {
  31. err := json.Unmarshal(response, obj)
  32. if err != nil {
  33. return fmt.Errorf("json Unmarshal Error, err=%v", err)
  34. }
  35. responseObj := reflect.ValueOf(obj)
  36. if !responseObj.IsValid() {
  37. return fmt.Errorf("obj is invalid")
  38. }
  39. commonError := responseObj.Elem().FieldByName("CommonError")
  40. if !commonError.IsValid() || commonError.Kind() != reflect.Struct {
  41. return fmt.Errorf("commonError is invalid or not struct")
  42. }
  43. errCode := commonError.FieldByName("ErrCode")
  44. errMsg := commonError.FieldByName("ErrMsg")
  45. if !errCode.IsValid() || !errMsg.IsValid() {
  46. return fmt.Errorf("errcode or errmsg is invalid")
  47. }
  48. if errCode.Int() != 0 {
  49. return &CommonError{
  50. apiName: apiName,
  51. ErrCode: errCode.Int(),
  52. ErrMsg: errMsg.String(),
  53. }
  54. }
  55. return nil
  56. }