package uerr // PayloadSentinel is an error factory whose errors carry a payload of type P. // Its New method creates errors with the sentinel's message. // Use the sentinel itself as the target of errors.Is to match the errors it created. type PayloadSentinel[P any] struct { msg string } // NewWithPayload returns a PayloadSentinel with the given message. func NewWithPayload[P any](msg string) *PayloadSentinel[P] { return &PayloadSentinel[P]{msg: msg} } // New creates an error that matches s, carries payload, and applies opts to it. func (s *PayloadSentinel[P]) New(payload P, opts ...ErrOption) error { e := &payloadError[P]{sentinel: s, payload: payload} for _, opt := range opts { opt(&e.base) } return e } // Error returns the message of the sentinel. func (s *PayloadSentinel[P]) Error() string { return s.msg } // Payload returns the first payload belonging to s in err's tree. // It examines err before its children, traversing children depth-first in order. func (s *PayloadSentinel[P]) Payload(err error) (P, bool) { var zero P if err == nil { return zero, false } if e, ok := err.(*payloadError[P]); ok && e.sentinel == s { return e.payload, true } for _, kid := range children(err) { if p, ok := s.Payload(kid); ok { return p, true } } return zero, false } type payloadError[P any] struct { sentinel *PayloadSentinel[P] payload P base } func (e *payloadError[P]) Error() string { return e.sentinel.msg } func (e *payloadError[P]) Is(target error) bool { t, ok := target.(*PayloadSentinel[P]) return ok && t == e.sentinel }