fix: API error message — parse JSON error body, show actual API message instead of raw status
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user