Handle API failures gracefully

This commit is contained in:
Ayooluwa Isaiah
2020-03-17 18:33:58 +01:00
parent 3a924cfc1a
commit 85e3791709

16
main.go
View File

@@ -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
}