fix: enhance error handling and reporting for API responses

- Replace direct reading of response body with error handling for reading
- Add JSON unmarshalling of the response body for better error reporting
- Improve error message format to include details from the JSON response

Signed-off-by: appleboy <appleboy.tw@gmail.com>
This commit is contained in:
appleboy
2025-03-08 20:57:02 +08:00
parent 464bf4772f
commit 3e0f7cf5df
+9 -3
View File
@@ -322,9 +322,15 @@ func (p *Plugin) SendMessage(ctx context.Context) error {
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
bodyBytes, _ := io.ReadAll(resp.Body)
bodyString := string(bodyBytes)
return fmt.Errorf("failed to send message, status code: %d, response: %s", resp.StatusCode, bodyString)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
var jsonResponse map[string]interface{}
if err := json.Unmarshal(bodyBytes, &jsonResponse); err != nil {
return fmt.Errorf("failed to unmarshal response body: %w", err)
}
return fmt.Errorf("failed to send message, status code: %d, error: %s, code: %v", resp.StatusCode, jsonResponse["message"], jsonResponse["code"])
}
return nil