storj/satellite/console/consoleweb/consoleapi/common.go
Moby von Briesen d999a963ca satellite/console/.../consoleapi: Standardize serveJSONError
This change removes all the separate implementations for
`apiservice.serveJSONError()` and defines one for every service to use
in `consoleapi/common.go`.

Change-Id: Iabf184e5cba69a98eb25936ce11ebd07f02c8ff3
2021-06-29 09:40:07 -04:00

41 lines
1022 B
Go

// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package consoleapi
import (
"encoding/json"
"net/http"
"github.com/zeebo/errs"
"go.uber.org/zap"
)
var (
// ErrUtils - console utils error type.
ErrUtils = errs.Class("console api utils")
)
// serveJSONError writes a JSON error to the response output stream.
func serveJSONError(log *zap.Logger, w http.ResponseWriter, status int, err error) {
switch status {
case http.StatusNoContent:
return
case http.StatusInternalServerError:
log.Error("returning error to client", zap.Int("code", status), zap.Error(err))
case http.StatusBadRequest:
log.Debug("returning error to client", zap.Int("code", status), zap.Error(err))
default:
log.Info("returning error to client", zap.Int("code", status), zap.Error(err))
}
w.WriteHeader(status)
err = json.NewEncoder(w).Encode(map[string]string{
"error": err.Error(),
})
if err != nil {
log.Error("failed to write json error response", zap.Error(ErrUtils.Wrap(err)))
}
}