fix: API error message — parse JSON error body, show actual API message instead of raw status

This commit is contained in:
2026-07-28 16:42:00 +08:00
parent 51d1e82ac5
commit 4e348031a6
+23 -13
View File
@@ -82,20 +82,9 @@ func (c *client) do(ctx context.Context, method, path string, body, result any)
return fmt.Errorf("read response: %w", err) 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 var apiResp apiResponse
if err := json.Unmarshal(respBody, &apiResp); err != nil { if err := json.Unmarshal(respBody, &apiResp); err == nil {
return fmt.Errorf("unmarshal response: %w", err) if resp.StatusCode >= 400 || apiResp.Code != 0 {
}
if apiResp.Code != 0 {
return &APIError{ return &APIError{
StatusCode: resp.StatusCode, StatusCode: resp.StatusCode,
Method: method, Method: method,
@@ -105,6 +94,14 @@ func (c *client) do(ctx context.Context, method, path string, body, result any)
APIMsg: apiResp.Msg, APIMsg: apiResp.Msg,
} }
} }
} else if resp.StatusCode >= 400 {
return &APIError{
StatusCode: resp.StatusCode,
Method: method,
URL: url,
Body: respBody,
}
}
if result != nil { if result != nil {
if err := json.Unmarshal(respBody, result); err != nil { if err := json.Unmarshal(respBody, result); err != nil {
@@ -126,7 +123,20 @@ type APIError struct {
func (e *APIError) Error() string { func (e *APIError) Error() string {
msg := e.APIMsg msg := e.APIMsg
if msg == "" { if msg == "" {
// 非 JSON 响应,截取 body 前 200 字符
body := string(e.Body)
if len(body) > 200 {
body = body[:200] + "..."
}
if body != "" {
msg = body
} else {
msg = http.StatusText(e.StatusCode) msg = http.StatusText(e.StatusCode)
} }
}
return msg return msg
} }
func (e *APIError) Detail() string {
return fmt.Sprintf("%s %s [%d]", e.Method, e.URL, e.StatusCode)
}