From 85e3791709becc7681c9ea999325efaa7b461b22 Mon Sep 17 00:00:00 2001 From: Ayooluwa Isaiah Date: Tue, 17 Mar 2020 18:33:58 +0100 Subject: [PATCH] Handle API failures gracefully --- main.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index fe1d38c..a51538b 100644 --- a/main.go +++ b/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 }