1535bbe673
Provides the means to serve an error to the user with a user-friendly error message (serveCustomJSONError). Auth API uses this when processing registration attempts. Previously, the error message was inferred by the client based on the status code of the response received from the server. However, if multiple distinct errors fit a certain status code, it was impossible to correctly interpret the error. Change-Id: I2f91e9c81ba1a4d14ba67e0b4b531a48800d4799
51 lines
1.3 KiB
Go
51 lines
1.3 KiB
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) {
|
|
serveCustomJSONError(log, w, status, err, err.Error())
|
|
}
|
|
|
|
// serveCustomJSONError writes a JSON error with a custom message to the response output stream.
|
|
func serveCustomJSONError(log *zap.Logger, w http.ResponseWriter, status int, err error, msg string) {
|
|
fields := []zap.Field{
|
|
zap.Int("code", status),
|
|
zap.String("message", msg),
|
|
zap.Error(err),
|
|
}
|
|
switch status {
|
|
case http.StatusNoContent:
|
|
return
|
|
case http.StatusInternalServerError:
|
|
log.Error("returning error to client", fields...)
|
|
case http.StatusBadRequest:
|
|
log.Debug("returning error to client", fields...)
|
|
default:
|
|
log.Info("returning error to client", fields...)
|
|
}
|
|
|
|
w.WriteHeader(status)
|
|
|
|
err = json.NewEncoder(w).Encode(map[string]string{
|
|
"error": msg,
|
|
})
|
|
if err != nil {
|
|
log.Error("failed to write json error response", zap.Error(ErrUtils.Wrap(err)))
|
|
}
|
|
}
|