From 6c5ba82b37b6b5e56c751d2ab7e930324105d187 Mon Sep 17 00:00:00 2001 From: Ted Pearson <1477390+tedpearson@users.noreply.github.com> Date: Sat, 22 Jun 2024 00:44:53 -0400 Subject: [PATCH] return ad hoc forecast errors in json api --- prometheus.go | 1 + server.go | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/prometheus.go b/prometheus.go index 9e8783d..abf7664 100644 --- a/prometheus.go +++ b/prometheus.go @@ -33,6 +33,7 @@ type PromResult struct { type PromResponse struct { Status string `json:"status"` + Error string `json:"error,omitempty"` Data struct { ResultType string `json:"resultType"` Result []PromResult `json:"result"` diff --git a/server.go b/server.go index 98c0670..3e3bcbc 100644 --- a/server.go +++ b/server.go @@ -69,15 +69,14 @@ func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) { if err != nil { fmt.Printf("Failed to parse form: %s", err) resp.WriteHeader(http.StatusBadRequest) + errorJson(err, resp) + return } params, err := s.ParseParams(req.Form) if err != nil { - fmt.Printf("Failed to parse params: %s", err) + fmt.Printf("Failed to parse params: %s\n", err) resp.WriteHeader(http.StatusBadRequest) - _, err = resp.Write([]byte("{}")) - if err != nil { - fmt.Printf("Error writing response to client: %+v\n", err) - } + errorJson(err, resp) return } @@ -85,6 +84,7 @@ func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) { if err != nil { fmt.Printf("Error getting forecast: %+v\n", err) resp.WriteHeader(http.StatusInternalServerError) + errorJson(err, resp) return } // convert to prometheus response. @@ -94,6 +94,22 @@ func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) { respJson, err := json.Marshal(promResponse) if err != nil { resp.WriteHeader(http.StatusInternalServerError) + errorJson(err, resp) + return + } + _, err = resp.Write(respJson) + if err != nil { + fmt.Printf("Error writing response to client: %+v\n", err) + } +} + +func errorJson(err error, resp http.ResponseWriter) { + respJson, err := json.Marshal(PromResponse{ + Status: "error", + Error: err.Error(), + }) + if err != nil { + fmt.Printf("Error marshalling json: %s\n", err) return } _, err = resp.Write(respJson)