Skip to content

Commit

Permalink
ResponseEmpty error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
glossd committed Nov 12, 2024
1 parent ebc2b72 commit df1e68a
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 1 deletion.
2 changes: 1 addition & 1 deletion fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ func Request[T any](url string, config ...Config) (T, *Error) {
var t T
typeOf := reflect.TypeOf(t)

if typeOf != nil && typeOf == typeFor[ResponseEmpty]() {
if typeOf != nil && typeOf == typeFor[ResponseEmpty]() && firstDigit(res.StatusCode) == 2 {
re := any(&t).(*ResponseEmpty)
re.Status = res.StatusCode
re.DuplicateHeaders = res.Header
Expand Down
5 changes: 5 additions & 0 deletions fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ func TestRequest_ResponseEmpty(t *testing.T) {
if res.Headers()["Content-type"] != "application/json" {
t.Errorf("wrong headers")
}

_, err = Request[ResponseEmpty]("400.error")
if err == nil || err.Unwrap().Error() != "Bad Request" {
t.Errorf("Even with ResponseEmpty error should read the body")
}
}

func TestPostString(t *testing.T) {
Expand Down
2 changes: 2 additions & 0 deletions mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ func mockDNS(url string, req *http.Request) *mockResponse {
return &mockResponse{Status: 200, Body: `[1, 2, 3]`}
case "my.ip":
return &mockResponse{Status: 200, Headers: map[string][]string{"Content-type": {"text/plain"}}, Body: `8.8.8.8`}
case "400.error":
return &mockResponse{Status: 400, Body: `Bad Request`}
case "echo.me":
body, err := io.ReadAll(req.Body)
if err != nil {
Expand Down

0 comments on commit df1e68a

Please sign in to comment.