Explorar el Código

fix: handle JSON parse error when API returns binary file instead of error JSON (#852)

Co-authored-by: tax <jia_deng@intsig.net>
zhangjiani hace 9 meses
padre
commit
d4a81916d5
Se han modificado 2 ficheros con 17 adiciones y 8 borrados
  1. 15 0
      util/error.go
  2. 2 8
      work/material/media.go

+ 15 - 0
util/error.go

@@ -68,3 +68,18 @@ func DecodeWithError(response []byte, obj interface{}, apiName string) error {
 	}
 	return nil
 }
+
+// HandleFileResponse 通用处理微信等接口返回:有时 JSON 错误,有时文件内容
+func HandleFileResponse(response []byte, apiName string) ([]byte, error) {
+	var commErr CommonError
+	if err := json.Unmarshal(response, &commErr); err == nil {
+		// 能解析成 JSON,判断是否为错误
+		if commErr.ErrCode != 0 {
+			commErr.apiName = apiName
+			return nil, &commErr
+		}
+		// 能解析成 JSON 且没错误码,极少情况(比如微信返回的业务数据是 JSON 但无 errcode 字段),可根据需要调整
+	}
+	// 不能解析成 JSON,或没错误码,直接返回原始内容
+	return response, nil
+}

+ 2 - 8
work/material/media.go

@@ -191,12 +191,6 @@ func (r *Client) GetTempFile(mediaID string) ([]byte, error) {
 		return nil, err
 	}
 
-	// 检查响应是否为错误信息
-	err = util.DecodeWithCommonError(response, "GetTempFile")
-	if err != nil {
-		return nil, err
-	}
-
-	// 如果不是错误响应,则返回原始数据
-	return response, nil
+	// 检查响应是否为错误信息,如果不是错误响应,则返回原始数据
+	return util.HandleFileResponse(response, "GetTempFile")
 }