Skip to content

Commit

Permalink
Introduce APIError type and make ErrorEvent.Err public
Browse files Browse the repository at this point in the history
This makes it a little bit easier to act on API errors that happen while
streaming.
  • Loading branch information
alexbakker authored and mattn committed May 4, 2024
1 parent 0dad347 commit d53cfea
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 24 deletions.
25 changes: 21 additions & 4 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,26 @@ package mastodon
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
)

type APIError struct {
prefix string
Message string
StatusCode int
}

func (e *APIError) Error() string {
errMsg := fmt.Sprintf("%s: %d %s", e.prefix, e.StatusCode, http.StatusText(e.StatusCode))
if e.Message == "" {
return errMsg
}

return fmt.Sprintf("%s: %s", errMsg, e.Message)
}

// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
file, err := os.Open(filename)
Expand Down Expand Up @@ -41,15 +55,18 @@ func Base64Encode(file *os.File) (string, error) {
func String(v string) *string { return &v }

func parseAPIError(prefix string, resp *http.Response) error {
errMsg := fmt.Sprintf("%s: %s", prefix, resp.Status)
res := APIError{
prefix: prefix,
StatusCode: resp.StatusCode,
}
var e struct {
Error string `json:"error"`
}

json.NewDecoder(resp.Body).Decode(&e)
if e.Error != "" {
errMsg = fmt.Sprintf("%s: %s", errMsg, e.Error)
res.Message = e.Error
}

return errors.New(errMsg)
return &res
}
12 changes: 10 additions & 2 deletions helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,23 @@ func TestString(t *testing.T) {
func TestParseAPIError(t *testing.T) {
// No api error.
r := ioutil.NopCloser(strings.NewReader(`<html><head><title>404</title></head></html>`))
err := parseAPIError("bad request", &http.Response{Status: "404 Not Found", Body: r})
err := parseAPIError("bad request", &http.Response{
Status: "404 Not Found",
StatusCode: http.StatusNotFound,
Body: r,
})
want := "bad request: 404 Not Found"
if err.Error() != want {
t.Fatalf("want %q but %q", want, err.Error())
}

// With api error.
r = ioutil.NopCloser(strings.NewReader(`{"error":"Record not found"}`))
err = parseAPIError("bad request", &http.Response{Status: "404 Not Found", Body: r})
err = parseAPIError("bad request", &http.Response{
Status: "404 Not Found",
StatusCode: http.StatusNotFound,
Body: r,
})
want = "bad request: 404 Not Found: Record not found"
if err.Error() != want {
t.Fatalf("want %q but %q", want, err.Error())
Expand Down
4 changes: 2 additions & 2 deletions streaming.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ type DeleteEvent struct{ ID ID }
func (e *DeleteEvent) event() {}

// ErrorEvent is a struct for passing errors to app.
type ErrorEvent struct{ err error }
type ErrorEvent struct{ Err error }

func (e *ErrorEvent) event() {}
func (e *ErrorEvent) Error() string { return e.err.Error() }
func (e *ErrorEvent) Error() string { return e.Err.Error() }

// Event is an interface passing events to app.
type Event interface {
Expand Down
12 changes: 6 additions & 6 deletions streaming_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ data: {"content": "foo"}
}
case *ErrorEvent:
passError = true
if event.err == nil {
t.Fatalf("should be fail: %v", event.err)
if event.Err == nil {
t.Fatalf("should be fail: %v", event.Err)
}
}
}
Expand Down Expand Up @@ -126,8 +126,8 @@ data: {"content": "foo"}
switch event := e.(type) {
case *ErrorEvent:
passError = true
if event.err == nil {
t.Fatalf("should be fail: %v", event.err)
if event.Err == nil {
t.Fatalf("should be fail: %v", event.Err)
}
case *UpdateEvent:
cnt++
Expand Down Expand Up @@ -183,8 +183,8 @@ func TestDoStreaming(t *testing.T) {
for e := range q {
if event, ok := e.(*ErrorEvent); ok {
passError = true
if event.err == nil {
t.Fatalf("should be fail: %v", event.err)
if event.Err == nil {
t.Fatalf("should be fail: %v", event.Err)
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions streaming_ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (c *WSClient) streamingWS(ctx context.Context, stream, tag string) (chan Ev
func (c *WSClient) handleWS(ctx context.Context, rawurl string, q chan Event) error {
conn, err := c.dialRedirect(rawurl)
if err != nil {
q <- &ErrorEvent{err: err}
q <- &ErrorEvent{Err: err}

// End.
return err
Expand All @@ -103,7 +103,7 @@ func (c *WSClient) handleWS(ctx context.Context, rawurl string, q chan Event) er
for {
select {
case <-ctx.Done():
q <- &ErrorEvent{err: ctx.Err()}
q <- &ErrorEvent{Err: ctx.Err()}

// End.
return ctx.Err()
Expand All @@ -113,7 +113,7 @@ func (c *WSClient) handleWS(ctx context.Context, rawurl string, q chan Event) er
var s Stream
err := conn.ReadJSON(&s)
if err != nil {
q <- &ErrorEvent{err: err}
q <- &ErrorEvent{Err: err}

// Reconnect.
break
Expand Down
14 changes: 7 additions & 7 deletions streaming_ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,13 @@ func wsTest(t *testing.T, q chan Event, cancel func()) {
t.Fatalf("want %q but %q", "1234567", events[3].(*DeleteEvent).ID)
}
if errorEvent, ok := events[4].(*ErrorEvent); !ok {
t.Fatalf("should be fail: %v", errorEvent.err)
t.Fatalf("should be fail: %v", errorEvent.Err)
}
if errorEvent, ok := events[5].(*ErrorEvent); !ok {
t.Fatalf("should be fail: %v", errorEvent.err)
t.Fatalf("should be fail: %v", errorEvent.Err)
}
if errorEvent, ok := events[6].(*ErrorEvent); !ok {
t.Fatalf("should be fail: %v", errorEvent.err)
t.Fatalf("should be fail: %v", errorEvent.Err)
}
}

Expand All @@ -168,7 +168,7 @@ func TestStreamingWS(t *testing.T) {
defer wg.Done()
e := <-q
if errorEvent, ok := e.(*ErrorEvent); !ok {
t.Errorf("should be fail: %v", errorEvent.err)
t.Errorf("should be fail: %v", errorEvent.Err)
}
}()
wg.Wait()
Expand Down Expand Up @@ -204,7 +204,7 @@ func TestHandleWS(t *testing.T) {
defer wg.Done()
e := <-q
if errorEvent, ok := e.(*ErrorEvent); !ok {
t.Errorf("should be fail: %v", errorEvent.err)
t.Errorf("should be fail: %v", errorEvent.Err)
}
}()
err := client.handleWS(context.Background(), ":", q)
Expand All @@ -219,7 +219,7 @@ func TestHandleWS(t *testing.T) {
defer wg.Done()
e := <-q
if errorEvent, ok := e.(*ErrorEvent); !ok {
t.Errorf("should be fail: %v", errorEvent.err)
t.Errorf("should be fail: %v", errorEvent.Err)
}
}()
err = client.handleWS(ctx, "ws://"+ts.Listener.Addr().String(), q)
Expand All @@ -232,7 +232,7 @@ func TestHandleWS(t *testing.T) {
defer wg.Done()
e := <-q
if errorEvent, ok := e.(*ErrorEvent); !ok {
t.Errorf("should be fail: %v", errorEvent.err)
t.Errorf("should be fail: %v", errorEvent.Err)
}
}()
client.handleWS(context.Background(), "ws://"+ts.Listener.Addr().String(), q)
Expand Down

0 comments on commit d53cfea

Please sign in to comment.