2022-11-21 18:58:42 +00:00
|
|
|
// Copyright (C) 2022 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
2023-06-28 14:06:32 +01:00
|
|
|
"context"
|
2022-11-21 18:58:42 +00:00
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"go.uber.org/zap"
|
2023-06-28 14:06:32 +01:00
|
|
|
|
|
|
|
"storj.io/common/http/requestid"
|
2022-11-21 18:58:42 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ServeJSONError writes a JSON error to the response output stream.
|
2023-06-28 14:06:32 +01:00
|
|
|
func ServeJSONError(ctx context.Context, log *zap.Logger, w http.ResponseWriter, status int, err error) {
|
|
|
|
ServeCustomJSONError(ctx, log, w, status, err, err.Error())
|
2022-11-21 18:58:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ServeCustomJSONError writes a JSON error with a custom message to the response output stream.
|
2023-06-28 14:06:32 +01:00
|
|
|
func ServeCustomJSONError(ctx context.Context, log *zap.Logger, w http.ResponseWriter, status int, err error, msg string) {
|
2022-11-21 18:58:42 +00:00
|
|
|
fields := []zap.Field{
|
|
|
|
zap.Int("code", status),
|
|
|
|
zap.String("message", msg),
|
|
|
|
zap.Error(err),
|
|
|
|
}
|
2023-06-28 14:06:32 +01:00
|
|
|
|
|
|
|
if requestID := requestid.FromContext(ctx); requestID != "" {
|
|
|
|
fields = append(fields, zap.String("requestID", requestID))
|
|
|
|
}
|
|
|
|
|
2022-11-21 18:58:42 +00:00
|
|
|
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...)
|
|
|
|
case http.StatusTooManyRequests:
|
|
|
|
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(err))
|
|
|
|
}
|
|
|
|
}
|