From 932a0a24ec2fca073052a3815000f757317cea7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Sat, 10 Jul 2021 00:12:01 +0200 Subject: [PATCH] client: Improve error handling Get error json struct from API. --- mailman/mailman_client.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/mailman/mailman_client.go b/mailman/mailman_client.go index 8e7fec0..17aaca5 100644 --- a/mailman/mailman_client.go +++ b/mailman/mailman_client.go @@ -20,6 +20,11 @@ type ClientCredentials struct { Password string } +type apiError struct { + Title string `json:"title"` + Description string `json:"description"` +} + func NewMailmanCLient(url string, username string, password string) (*Client, error) { httpClient := &http.Client{ Timeout: time.Second * 3, @@ -122,14 +127,17 @@ func (client *Client) sendRequest(req *http.Request) ([]byte, error) { } defer resp.Body.Close() - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("API error code: %d", resp.StatusCode) - } - responseBody, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } + if resp.StatusCode >= 400 { + var error apiError + json.Unmarshal(responseBody, &error) + + return nil, fmt.Errorf("API error %s: %s", error.Title, error.Description) + } + return responseBody, nil } -- 2.44.0