Skip to content

Commit 3ffe918

Browse files
Merge pull request #18 from iktakahiro/add-implementation-error-interface
Add RestError Struct for an error handling.
2 parents e814e65 + 564414e commit 3ffe918

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

rest.go

+10
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ type Request struct {
2929
Body []byte
3030
}
3131

32+
// RestError is a struct for an error handling.
33+
type RestError struct {
34+
Response *Response
35+
}
36+
37+
// Error is the implementation of the error interface.
38+
func (e *RestError) Error() string {
39+
return e.Response.Body
40+
}
41+
3242
// DefaultClient is used if no custom HTTP client is defined
3343
var DefaultClient = &Client{HTTPClient: http.DefaultClient}
3444

rest_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,27 @@ func TestCustomHTTPClient(t *testing.T) {
164164
t.Error("We did not receive the Timeout error")
165165
}
166166
}
167+
168+
func TestRestError(t *testing.T) {
169+
headers := make(map[string][]string)
170+
headers["Content-Type"] = []string{"application/json"}
171+
172+
response := &Response{
173+
StatusCode: 400,
174+
Body: `{"result": "failure"}`,
175+
Headers: headers,
176+
}
177+
178+
restErr := &RestError{Response: response}
179+
180+
var err error
181+
err = restErr
182+
183+
if _, ok := err.(*RestError); !ok {
184+
t.Error("RestError does not satisfiy the error interface.")
185+
}
186+
187+
if err.Error() != `{"result": "failure"}` {
188+
t.Error("Invalid error message.")
189+
}
190+
}

0 commit comments

Comments
 (0)