Skip to content
This repository has been archived by the owner on Jan 17, 2025. It is now read-only.

Commit

Permalink
Update api error handling
Browse files Browse the repository at this point in the history
Apparently the api may return lists of error data structures.

Signed-off-by: Dimitrios Karagiannis <dhkarag@gmail.com>
  • Loading branch information
alkar committed Oct 10, 2019
1 parent 17ccb2b commit 9595dc5
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions megaport/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,31 +176,40 @@ func (c *Client) do(req *http.Request, data interface{}) error {
if err != nil {
return err
}
r := megaportResponse{}
if resp.StatusCode == http.StatusNotFound {
return ErrNotFound
}
if resp.StatusCode != http.StatusOK {
if err = parseResponseBody(resp, &r); err != nil {
r := megaportResponse{}
if err := parseResponseBody(resp, &r); err != nil {
return err
}
switch e := r.Data.(type) {
case string:
return fmt.Errorf("megaport-api: %s (%s)", r.Message, e)
case map[string]interface{}:
errData := &strings.Builder{}
for k, v := range e {
if _, err := fmt.Fprintf(errData, "%s=%#v ", k, v); err != nil {
return err
}
return fmt.Errorf("megaport-api: %s: %w", r.Message, responseDataToError(r.Data))
}
return parseResponseBody(resp, &megaportResponse{Data: data})
}

func responseDataToError(d interface{}) error {
switch e := d.(type) {
case string:
return fmt.Errorf("%s", e)
case map[string]interface{}:
errData := &strings.Builder{}
for k, v := range e {
if _, err := fmt.Fprintf(errData, "%s=%#v ", k, v); err != nil {
return err
}
return fmt.Errorf("megaport-api: %s (%s)", r.Message, strings.TrimSpace(errData.String()))
default:
return fmt.Errorf("megaport-api: %s (cannot process data of type %T: %#v", r.Message, e, e)
}
return fmt.Errorf("%s", strings.TrimSpace(errData.String()))
case []interface{}:
errors := make([]string, len(e))
for i, v := range e {
errors[i] = responseDataToError(v).Error()
}
return fmt.Errorf("%d errors: ['%s']", len(e), strings.Join(errors, "', '"))
default:
return fmt.Errorf("cannot process error data of type %T: %#v", e, e)
}
r.Data = data
return parseResponseBody(resp, &r)
}

func parseResponseBody(resp *http.Response, data interface{}) error {
Expand Down

0 comments on commit 9595dc5

Please sign in to comment.