From 901e6d1f82ee5298fbb7432ad412ac7e09371695 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Wed, 25 Jul 2018 13:17:10 +0100 Subject: [PATCH] Review feedback. Signed-off-by: Tom Wilkie --- web/api/v1/api.go | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/web/api/v1/api.go b/web/api/v1/api.go index fe9c5ed4e..3b81b81f9 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -843,7 +843,18 @@ func (api *API) respond(w http.ResponseWriter, data interface{}) { } func (api *API) respondError(w http.ResponseWriter, apiErr *apiError, data interface{}) { - w.Header().Set("Content-Type", "application/json") + json := jsoniter.ConfigCompatibleWithStandardLibrary + b, err := json.Marshal(&response{ + Status: statusError, + ErrorType: apiErr.typ, + Error: apiErr.err.Error(), + Data: data, + }) + if err != nil { + level.Error(api.logger).Log("msg", "error marshalling json response", "err", err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } var code int switch apiErr.typ { @@ -860,22 +871,9 @@ func (api *API) respondError(w http.ResponseWriter, apiErr *apiError, data inter default: code = http.StatusInternalServerError } - w.WriteHeader(code) - json := jsoniter.ConfigCompatibleWithStandardLibrary - b, err := json.Marshal(&response{ - Status: statusError, - ErrorType: apiErr.typ, - Error: apiErr.err.Error(), - Data: data, - }) - if err != nil { - return - } - if err != nil { - level.Error(api.logger).Log("msg", "error marshalling json response", "err", err) - return - } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) if n, err := w.Write(b); err != nil { level.Error(api.logger).Log("msg", "error writing response", "n", n, "err", err) }