Merge pull request #27 from 178inaba/api_error

Fix to parse API error
This commit is contained in:
mattn 2017-04-19 14:52:50 +09:00 committed by GitHub
commit 8dfdc289a2
4 changed files with 22 additions and 8 deletions

View File

@ -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

View File

@ -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)
}

View File

@ -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 {

View File

@ -4,7 +4,6 @@ import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
@ -94,8 +93,8 @@ func (c *Client) streaming(ctx context.Context, p string, tag string) (chan Even
if err == nil {
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)
if resp != nil && resp.StatusCode != http.StatusOK {
err = parseAPIError("bad request", resp)
}
}
if err == nil {