Files

168 lines
4.6 KiB
Go

package httperror
import (
"fmt"
"maps"
"net/http"
"strings"
"sync"
"github.com/effective-security/porto/xhttp/correlation"
"github.com/effective-security/porto/xhttp/header"
"github.com/ugorji/go/codec"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ManyError identifies many errors from API.
type ManyError struct {
// HTTPStatus contains the HTTP status code that should be used for this error
HTTPStatus int `json:"-"`
RPCStatus codes.Code `json:"-"`
// Code identifies the particular error condition [for programatic consumers]
Code string `json:"code,omitempty"`
// RequestID identifies the request ID
RequestID string `json:"request_id,omitempty"`
// Message is an textual description of the error
Message string `json:"message,omitempty"`
// Errors holds the individual errors keyed by the caller-chosen key
// passed to Add (for example a field or item name).
Errors map[string]*Error `json:"errors,omitempty"`
// Cause is the first original error
cause error `json:"-"`
lock sync.Mutex `json:"-"`
}
// GRPCStatus returns the gRPC status derived from Code and Message, with
// the Code and RequestID details that Error.GRPCStatus attaches, so a
// *ManyError can be returned from gRPC handlers.
func (m *ManyError) GRPCStatus() *status.Status {
return newStatus(statusCode[m.Code], m.Message, m.Code, m.RequestID)
}
// Error returns "code: message" (prefixed with the request ID when set) or,
// when Code is empty, the nested errors joined by ";".
func (m *ManyError) Error() string {
if m == nil {
return "nil"
}
if m.Code != "" {
if m.RequestID != "" {
return fmt.Sprintf("request %s: %s: %s", m.RequestID, m.Code, m.Message)
}
return fmt.Sprintf("%s: %s", m.Code, m.Message)
}
var errs []string
for _, e := range m.Errors {
errs = append(errs, e.Error())
}
return strings.Join(errs, ";")
}
// CorrelationID implements the Correlation interface,
// and returns request ID
func (m *ManyError) CorrelationID() string {
return m.RequestID
}
// Cause returns original error
func (m *ManyError) Cause() error {
return m.cause
}
// WithCause adds the cause error
func (m *ManyError) WithCause(err error) *ManyError {
m.cause = err
return m
}
// NewMany returns a ManyError with the given HTTP status and code and an
// empty Errors map; add nested errors with Add.
func NewMany(status int, code string, msgFormat string, vals ...any) *ManyError {
return &ManyError{
HTTPStatus: status,
RPCStatus: statusCode[code],
Code: code,
Message: fmt.Sprintf(msgFormat, vals...),
Errors: make(map[string]*Error),
}
}
// Add records err under key (replacing any previous entry) and returns the
// receiver. Non-*Error values are wrapped as CodeUnexpected. The first error
// added becomes the Cause. Add is safe for concurrent use and allocates a
// new ManyError when called on a nil receiver.
func (m *ManyError) Add(key string, err error) *ManyError {
if m == nil {
m = new(ManyError)
}
m.lock.Lock()
defer m.lock.Unlock()
if m.Errors == nil {
m.Errors = make(map[string]*Error)
}
if m.cause == nil {
m.cause = err
}
if gErr, ok := err.(*Error); ok {
m.Errors[key] = gErr
} else {
m.Errors[key] = &Error{
Code: CodeUnexpected,
Message: err.Error(),
cause: err,
}
}
return m
}
// HasErrors check if ManyError has any nested error associated with it.
func (m *ManyError) HasErrors() bool {
return len(m.Errors) > 0
}
// WriteHTTPResponse writes the error and its nested Errors as an
// application/json body with HTTPStatus; see Error.WriteHTTPResponse. The
// receiver is not modified: when RequestID is empty the body carries the
// request's correlation ID. The nested errors are snapshotted under the Add
// lock, which is released before anything is written, so a slow client
// never blocks other users of a shared ManyError.
func (m *ManyError) WriteHTTPResponse(w http.ResponseWriter, r *http.Request) {
body := m.snapshot()
if body.RequestID == "" {
body.RequestID = correlation.ID(r.Context())
}
// TODO: check r.Accept
w.Header().Set(header.ContentType, header.ApplicationJSON)
w.WriteHeader(body.HTTPStatus)
_ = codec.NewEncoder(w, encoderHandle(shouldPrettyPrint(r))).Encode(body)
}
// snapshot returns a copy of the exported fields with a clone of the Errors
// map, taken under the lock. The lock itself is not copied.
func (m *ManyError) snapshot() *ManyError {
m.lock.Lock()
defer m.lock.Unlock()
return &ManyError{
HTTPStatus: m.HTTPStatus,
RPCStatus: m.RPCStatus,
Code: m.Code,
RequestID: m.RequestID,
Message: m.Message,
Errors: maps.Clone(m.Errors),
}
}