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)
|
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 {
|
||||||
}
|
return &APIError{
|
||||||
if apiResp.Code != 0 {
|
StatusCode: resp.StatusCode,
|
||||||
|
Method: method,
|
||||||
|
URL: url,
|
||||||
|
Body: respBody,
|
||||||
|
APICode: apiResp.Code,
|
||||||
|
APIMsg: apiResp.Msg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if resp.StatusCode >= 400 {
|
||||||
return &APIError{
|
return &APIError{
|
||||||
StatusCode: resp.StatusCode,
|
StatusCode: resp.StatusCode,
|
||||||
Method: method,
|
Method: method,
|
||||||
URL: url,
|
URL: url,
|
||||||
Body: respBody,
|
Body: respBody,
|
||||||
APICode: apiResp.Code,
|
|
||||||
APIMsg: apiResp.Msg,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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 == "" {
|
||||||
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
|
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