From 89a4b0be6ee0d6a0eec97a565a2760e57247c436 Mon Sep 17 00:00:00 2001 From: John Olheiser Date: Thu, 28 Apr 2022 10:56:33 +0800 Subject: [PATCH] Return error message for 4xx errors (#583) Resolves #582 Resolves #551 As noted in both issues, we _could_ put the `resp.Body` back, however I think this should also suffice, as it will return error messages when appropriate based on the JSON response. Co-authored-by: jolheiser Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/583 Reviewed-by: Lunny Xiao Reviewed-by: 6543 <6543@obermui.de> Co-authored-by: John Olheiser Co-committed-by: John Olheiser --- gitea/client.go | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/gitea/client.go b/gitea/client.go index 64d3c79..c07e550 100644 --- a/gitea/client.go +++ b/gitea/client.go @@ -9,7 +9,6 @@ import ( "bytes" "context" "encoding/json" - "errors" "fmt" "io" "io/ioutil" @@ -269,27 +268,24 @@ func statusCodeToErr(resp *Response) (body []byte, err error) { return nil, fmt.Errorf("body read on HTTP error %d: %v", resp.StatusCode, err) } - switch resp.StatusCode { - case 403: - return data, errors.New("403 Forbidden") - case 404: - return data, errors.New("404 Not Found") - case 409: - return data, errors.New("409 Conflict") - case 422: - return data, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) - } - - path := resp.Request.URL.Path - method := resp.Request.Method - header := resp.Request.Header + // Try to unmarshal and get an error message errMap := make(map[string]interface{}) if err = json.Unmarshal(data, &errMap); err != nil { // when the JSON can't be parsed, data was probably empty or a // plain string, so we try to return a helpful error anyway + path := resp.Request.URL.Path + method := resp.Request.Method + header := resp.Request.Header return data, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data)) } - return data, errors.New(errMap["message"].(string)) + + if msg, ok := errMap["message"]; ok { + return data, fmt.Errorf("%v", msg) + } + + // If no error message, at least give status and data + return data, fmt.Errorf("%s: %s", resp.Status, string(data)) + } func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, *Response, error) {