diff --git a/apps.go b/apps.go index 1dd50a5..01b976e 100644 --- a/apps.go +++ b/apps.go @@ -3,7 +3,6 @@ package mastodon import ( "context" "encoding/json" - "fmt" "net/http" "net/url" "path" @@ -64,7 +63,7 @@ func RegisterApp(ctx context.Context, appConfig *AppConfig) (*Application, error defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("bad request: %v", resp.Status) + return nil, parseAPIError("bad request", resp) } var app Application diff --git a/helper.go b/helper.go index c9fefe9..05af20f 100644 --- a/helper.go +++ b/helper.go @@ -2,6 +2,9 @@ package mastodon import ( "encoding/base64" + "encoding/json" + "errors" + "fmt" "net/http" "os" ) @@ -36,3 +39,17 @@ func Base64Encode(file *os.File) (string, error) { // String is a helper function to get the pointer value of a string. func String(v string) *string { return &v } + +func parseAPIError(prefix string, resp *http.Response) error { + errMsg := fmt.Sprintf("%s: %s", prefix, resp.Status) + var e struct { + Error string `json:"error"` + } + + json.NewDecoder(resp.Body).Decode(&e) + if e.Error != "" { + errMsg = fmt.Sprintf("%s: %s", errMsg, e.Error) + } + + return errors.New(errMsg) +} diff --git a/mastodon.go b/mastodon.go index ce4265d..4a20c55 100644 --- a/mastodon.go +++ b/mastodon.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "fmt" "io" "mime/multipart" "net/http" @@ -131,7 +130,7 @@ func (c *Client) doAPI(ctx context.Context, method string, uri string, params in } } if resp.StatusCode != http.StatusOK { - return fmt.Errorf("bad request: %v", resp.Status) + return parseAPIError("bad request", resp) } else if res == nil { return nil } @@ -175,7 +174,7 @@ func (c *Client) Authenticate(ctx context.Context, username, password string) er defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return fmt.Errorf("bad authorization: %v", resp.Status) + return parseAPIError("bad authorization", resp) } res := struct { diff --git a/streaming.go b/streaming.go index 6df8148..005920c 100644 --- a/streaming.go +++ b/streaming.go @@ -4,7 +4,6 @@ import ( "bufio" "context" "encoding/json" - "fmt" "io" "net/http" "net/url" @@ -95,7 +94,7 @@ func (c *Client) streaming(ctx context.Context, p string, tag string) (chan Even req.Header.Set("Authorization", "Bearer "+c.config.AccessToken) resp, err = c.Do(req) if resp != nil && resp.StatusCode != 200 { - err = fmt.Errorf("bad request: %v", resp.Status) + err = parseAPIError("bad request", resp) } } if err == nil {