Handle API failures gracefully
This commit is contained in:
16
main.go
16
main.go
@@ -67,6 +67,12 @@ func (s *Search) CurrentPage() int {
|
||||
return s.NextPage - 1
|
||||
}
|
||||
|
||||
type NewsAPIError struct {
|
||||
Status string `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func indexHandler(w http.ResponseWriter, r *http.Request) {
|
||||
tpl.Execute(w, nil)
|
||||
}
|
||||
@@ -108,7 +114,15 @@ func searchHandler(w http.ResponseWriter, r *http.Request) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
newError := &NewsAPIError{}
|
||||
err := json.NewDecoder(resp.Body).Decode(newError)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, "Unexpected server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, newError.Message, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user