Skip to content

Commit fb3b439

Browse files
committed
Add detailed error information to method responses
1 parent e1272e6 commit fb3b439

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

+13
Original file line numberDiff line numberDiff line change
@@ -203,3 +203,16 @@ err := client.Delete(microcms.DeleteParams{
203203
ContentID: "my-content-id",
204204
})
205205
```
206+
207+
### Error Handling
208+
209+
```go
210+
data, err := client.Get(ctx, "endpoint", nil)
211+
if err != nil {
212+
if httpErr, ok := err.(*sdk.HttpResponseError); ok {
213+
fmt.Printf("HTTP Status Code: %d\n", httpErr.Response.StatusCode)
214+
fmt.Printf("Error Message: %s\n", httpErr.ErrorMessage)
215+
}
216+
return
217+
}
218+
```

client.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ func sendRequest(c *Client, req *http.Request, data interface{}) error {
7272
if err != nil {
7373
return fmt.Errorf("microCMS connection error: %w", err)
7474
}
75-
return fmt.Errorf("microCMS response error: %s", errorMessage)
75+
return &HttpResponseError{
76+
Response: res,
77+
ErrorMessage: string(errorMessage),
78+
}
7679
}
7780

7881
if strings.Contains(res.Header.Get("Content-Type"), "application/json") {
@@ -83,3 +86,12 @@ func sendRequest(c *Client, req *http.Request, data interface{}) error {
8386

8487
return nil
8588
}
89+
90+
type HttpResponseError struct {
91+
Response *http.Response
92+
ErrorMessage string
93+
}
94+
95+
func (r *HttpResponseError) Error() string {
96+
return fmt.Sprintf("response error: StatusCode=%d %s", r.Response.StatusCode, r.ErrorMessage)
97+
}

0 commit comments

Comments
 (0)