From d4a81916d57dce92a06be3ff5d85122b25ed1519 Mon Sep 17 00:00:00 2001 From: zhangjiani <15646517+Xkta@users.noreply.github.com> Date: Sun, 14 Sep 2025 19:47:00 +0800 Subject: [PATCH] fix: handle JSON parse error when API returns binary file instead of error JSON (#852) Co-authored-by: tax --- util/error.go | 15 +++++++++++++++ work/material/media.go | 10 ++-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/util/error.go b/util/error.go index 72b772f..4354d32 100644 --- a/util/error.go +++ b/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 +} diff --git a/work/material/media.go b/work/material/media.go index 551eeee..e11a52d 100644 --- a/work/material/media.go +++ b/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") }