From 4e348031a6bf284067e59435a5bf8aa1577f6645 Mon Sep 17 00:00:00 2001 From: NightStar Date: Tue, 28 Jul 2026 16:42:00 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20API=20error=20message=20=E2=80=94=20pars?= =?UTF-8?q?e=20JSON=20error=20body,=20show=20actual=20API=20message=20inst?= =?UTF-8?q?ead=20of=20raw=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/provider/rainyun/client.go | 42 ++++++++++++++++++----------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/internal/provider/rainyun/client.go b/internal/provider/rainyun/client.go index 6c48fd9..bb76ee1 100644 --- a/internal/provider/rainyun/client.go +++ b/internal/provider/rainyun/client.go @@ -82,27 +82,24 @@ func (c *client) do(ctx context.Context, method, path string, body, result any) return fmt.Errorf("read response: %w", err) } - if resp.StatusCode >= 400 { - return &APIError{ - StatusCode: resp.StatusCode, - Method: method, - URL: url, - Body: respBody, - } - } - var apiResp apiResponse - if err := json.Unmarshal(respBody, &apiResp); err != nil { - return fmt.Errorf("unmarshal response: %w", err) - } - if apiResp.Code != 0 { + if err := json.Unmarshal(respBody, &apiResp); err == nil { + if resp.StatusCode >= 400 || apiResp.Code != 0 { + return &APIError{ + StatusCode: resp.StatusCode, + Method: method, + URL: url, + Body: respBody, + APICode: apiResp.Code, + APIMsg: apiResp.Msg, + } + } + } else if resp.StatusCode >= 400 { return &APIError{ StatusCode: resp.StatusCode, Method: method, URL: url, Body: respBody, - APICode: apiResp.Code, - APIMsg: apiResp.Msg, } } @@ -126,7 +123,20 @@ type APIError struct { func (e *APIError) Error() string { msg := e.APIMsg if msg == "" { - msg = http.StatusText(e.StatusCode) + // 非 JSON 响应,截取 body 前 200 字符 + body := string(e.Body) + if len(body) > 200 { + body = body[:200] + "..." + } + if body != "" { + msg = body + } else { + msg = http.StatusText(e.StatusCode) + } } return msg } + +func (e *APIError) Detail() string { + return fmt.Sprintf("%s %s [%d]", e.Method, e.URL, e.StatusCode) +}