Skip to content

Commit b71268b

Browse files
authored
Improve ErrorResponse's Error() implementation to be more specific. (#81)
It turns out most clients rely on the built-in error interface, and don't explicitly cast to ErrorResponse. Those clients would only see a very generic "The MessageBird API is currently unavailable" message. After this change, Error() will return a concatenated list of the actual error descriptions returned by the MessageBird APIs. If desired, clients can still cast to ErrorReponse to inspect the "code" and "param" fields for the individual API errors
1 parent fd2581d commit b71268b

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

error.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
package messagebird
22

3-
const (
4-
apiErrMessage = "The MessageBird API returned an error"
3+
import (
4+
"fmt"
5+
"strings"
56
)
67

78
// Error holds details including error code, human readable description and optional parameter that is related to the error.
@@ -23,5 +24,9 @@ type ErrorResponse struct {
2324

2425
// Error implements error interface.
2526
func (r ErrorResponse) Error() string {
26-
return apiErrMessage
27+
var inners []string
28+
for _, inner := range r.Errors {
29+
inners = append(inners, inner.Error())
30+
}
31+
return fmt.Sprintf("API errors: %s", strings.Join(inners, ", "))
2732
}

error_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package messagebird
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestError(t *testing.T) {
8+
t.Run("Single", func(t *testing.T) {
9+
errRes := ErrorResponse{
10+
Errors: []Error{
11+
Error{
12+
Code: 42,
13+
Description: "something bad",
14+
Parameter: "foo",
15+
},
16+
},
17+
}
18+
if s := errRes.Error(); s != "API errors: something bad" {
19+
t.Errorf("Got %q, expected API response: something bad", s)
20+
}
21+
})
22+
23+
t.Run("Multiple", func(t *testing.T) {
24+
errRes := ErrorResponse{
25+
Errors: []Error{
26+
Error{
27+
Code: 42,
28+
Description: "something bad",
29+
Parameter: "foo",
30+
},
31+
Error{
32+
Code: 42,
33+
Description: "something else",
34+
Parameter: "foo",
35+
},
36+
},
37+
}
38+
if s := errRes.Error(); s != "API errors: something bad, something else" {
39+
t.Errorf("Got %q, expected API response: something bad, something else", s)
40+
}
41+
})
42+
}

0 commit comments

Comments
 (0)