Skip to content

Commit

Permalink
return ad hoc forecast errors in json api
Browse files Browse the repository at this point in the history
  • Loading branch information
tedpearson committed Jun 22, 2024
1 parent 0a0e19d commit 6c5ba82
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
1 change: 1 addition & 0 deletions prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
26 changes: 21 additions & 5 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,22 @@ 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
}

forecast, err := s.Dispatcher.GetForecast(params.Location, params.Source, params.AdHoc)
if err != nil {
fmt.Printf("Error getting forecast: %+v\n", err)
resp.WriteHeader(http.StatusInternalServerError)
errorJson(err, resp)
return
}
// convert to prometheus response.
Expand All @@ -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)
Expand Down

0 comments on commit 6c5ba82

Please sign in to comment.