Skip to content

Commit 3b34a72

Browse files
committed
fix: Gracefully handle HTTP errors
Return error in case of an unexpeted response.
1 parent 84ff3b4 commit 3b34a72

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

hackernews.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package opinions
33
import (
44
"context"
55
"encoding/json"
6+
"fmt"
67
"io"
78
"net/url"
89
"time"
@@ -38,6 +39,10 @@ func SearchHackerNews(ctx context.Context, client http.Client, query string) ([]
3839
}
3940
defer r.Body.Close()
4041

42+
if r.StatusCode != http.StatusOK {
43+
return discussions, fmt.Errorf("cannot search Hacker News: status code %d", r.StatusCode)
44+
}
45+
4146
body, err := io.ReadAll(r.Body)
4247
if err != nil {
4348
return discussions, err

http/client.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import (
88
"runtime"
99
)
1010

11+
// Selected HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
12+
const (
13+
StatusOK = 200
14+
)
15+
1116
// A Client is an HTTP client.
1217
type Client struct {
1318
defaultClient http.Client

lobsters.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package opinions
22

33
import (
44
"context"
5+
"fmt"
56
"net/url"
67
"strconv"
78

@@ -27,6 +28,10 @@ func SearchLobsters(ctx context.Context, client http.Client, query string) ([]Di
2728
}
2829
defer r.Body.Close()
2930

31+
if r.StatusCode != http.StatusOK {
32+
return discussions, fmt.Errorf("cannot search Lobsters: status code %d", r.StatusCode)
33+
}
34+
3035
body, err := html.Parse(r.Body)
3136
if err != nil {
3237
return discussions, err

0 commit comments

Comments
 (0)