Documentation
¶
Overview ¶
Package errors adds typed error semantics on top of the stdlib errors package: a stable machine-readable Code, an optional HTTP status hint, and Wrap/Is/As support. Consumers who just want stdlib behaviour can keep using errors — this package is opt-in for structured errors.
Typical usage in a service:
ErrNotFound = errors.New(errors.CodeNotFound, "not found")
ErrConflict = errors.New(errors.CodeConflict, "conflict")
func GetUser(id string) (*User, error) {
u, err := repo.Find(id)
if err != nil {
return nil, errors.Wrap(err, ErrNotFound, "user %q", id)
}
return u, nil
}
// In an HTTP handler:
if err := svc.Do(); err != nil {
status := errors.HTTPStatus(err) // 404 for ErrNotFound
code := errors.CodeOf(err) // "not_found"
// ...
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HTTPStatus ¶
HTTPStatus maps err's code to a suggested HTTP status. Unknown codes fall through to 500. Consumers who want app-specific mappings should bring their own function; this is a reasonable default only.
Types ¶
type Code ¶
type Code string
Code is a stable machine-readable identifier. Consumers define their own codes as constants; hex ships the common ones as a starting point.
const ( CodeInternal Code = "internal" CodeInvalidArgument Code = "invalid_argument" CodeNotFound Code = "not_found" CodeConflict Code = "conflict" CodeForbidden Code = "forbidden" CodeRateLimited Code = "rate_limited" CodeTimeout Code = "timeout" )
Common code constants. Consumers may extend with their own; these cover the most frequent HTTP-mappable failures.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is the typed error type. It carries a Code, a message, and an optional wrapped cause.
func Wrap ¶
Wrap attaches cause to a new Error carrying msg. The result satisfies errors.Is / errors.As against both the target sentinel and the cause. If target is nil, cause's own code is preserved when possible.
func (*Error) Error ¶
Error returns the fully composed message. If a cause is attached, its message follows a colon.