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