Structured errors for Go: every error carries a code, an HTTP status, optional field errors and the errors it wraps, and it still works with the standard errors package.
Made by Pixie. Project page: https://pixie-sh.github.io/errors-go/
go get github.com/pixie-sh/errors-gopackage main
import (
"fmt"
"github.com/pixie-sh/errors-go"
)
func findUser(id string) error {
return errors.New("user %s not found", id, errors.NotFoundErrorCode)
}
func main() {
err := findUser("42")
fmt.Println(err) // NotFoundError-40404 user 42 not found
if e, ok := errors.As(err); ok {
fmt.Println(e.Code.Name, e.Code.Value, e.GetHTTPStatus()) // NotFoundError 40404 404
}
}The error code, field errors and wrapped errors are passed as extra arguments to New, in any position. Everything else is treated as a format argument.
An ErrorCode is a name plus a number. The last three digits of the number are the HTTP status, so one value answers both "what went wrong" and "what do I return".
var OrderLockedErrorCode = errors.NewErrorCode("OrderLockedError", 40000+errors.HTTPConflict)
err := errors.New("order %d is locked", 7, OrderLockedErrorCode)
fmt.Println(err, err.GetHTTPStatus()) // OrderLockedError-40409 order 7 is locked 409NewErrorCode panics if the last three digits are not a valid HTTP status, so a bad code fails at start-up. An error created without a code gets UnknownErrorCode (500).
The package ships common codes, grouped by range:
| Range | Group | Examples |
|---|---|---|
| 40000 | user input and database | NotFoundErrorCode, UnauthorizedErrorCode, InvalidFormDataCode, QueryDuplicatedKeyErrorCode |
| 50000 | system | UnknownErrorCode, DBErrorCode, JoinedErrorCode |
| 55000 | streams | ProducerErrorCode, RateLimitErrorCode |
| 60000 | state machine | StateMachineInvalidTransitionErrorCode |
| 90000 | generic | GenericErrorCode |
Wrap nests the original error and inherits its code unless you pass a new one.
err := errors.Wrap(findUser("42"), "loading profile")
fmt.Println(err)
// NotFoundError-40404 loading profile; NotFoundError-40404 user 42 not found
fmt.Println(err.GetHTTPStatus()) // 404Errors from other packages wrap the same way:
err := errors.Wrap(io.ErrUnexpectedEOF, "reading body", errors.ErrorUnmarshallBodyErrorCode)
fmt.Println(err.GetHTTPStatus()) // 422%w is supported in the message as well: errors.New("reading body: %w", io.ErrUnexpectedEOF).
*Error implements Unwrap and Is, so errors.Is and errors.As from the standard library keep working. Is matches on the error code across the whole nested tree.
import stderrors "errors"
wrapped := errors.Wrap(io.ErrUnexpectedEOF, "reading body")
stderrors.Is(wrapped, io.ErrUnexpectedEOF) // true
notFound := errors.New("", errors.NotFoundErrorCode)
stderrors.Is(errors.Wrap(findUser("42"), "loading profile"), notFound) // trueif e, ok := errors.Has(err, errors.NotFoundErrorCode); ok {
// e is the *Error carrying that code
}Pass true as the third argument to also search inside joined errors.
err := errors.NewValidationError("invalid signup",
&errors.FieldError{Field: "email", Rule: "email", Message: "must be a valid email"},
&errors.FieldError{Field: "age", Rule: "min", Param: "18", Message: "must be at least 18"},
)The code defaults to InvalidFormDataCode (422) and the JSON form is ready to return from an API:
{
"code": "InvalidFormDataError-40422",
"message": "invalid signup",
"field_errors": [
{ "field": "email", "rule": "email", "rule_param": "", "message": "must be a valid email" },
{ "field": "age", "rule": "min", "rule_param": "18", "message": "must be at least 18" }
]
}Join drops nil values. It returns nil when nothing is left, the error itself when one is left, and a JoinedErrorCode error otherwise.
err := errors.Join(findUser("1"), nil, lockedErr)
_, found := errors.Has(err, OrderLockedErrorCode, true) // true
stderrors.Is(err, lockedErr) // true
errors.Join(nil, nil) == nil // trueErrors marshal and unmarshal with their code and nested errors, so they survive a trip between services.
b, _ := json.Marshal(errors.Wrap(findUser("42"), "loading profile"))
// {"code":"NotFoundError-40404","message":"loading profile","nested_error":[{"code":"NotFoundError-40404","message":"user 42 not found"}]}
var back errors.Error
_ = json.Unmarshal(b, &back)
back.GetHTTPStatus() // 404func writeError(w http.ResponseWriter, err error) {
e, ok := errors.As(err)
if !ok {
e = errors.Wrap(err, "unexpected error")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(e.GetHTTPStatus())
_ = json.NewEncoder(w).Encode(e)
}When DEBUG_MODE is active (see logger-go), every error records the stack and the caller in Trace, which is included in the JSON as stack_trace. It is off otherwise, so production errors stay small.
errors.Must(err) panics when err is not nil. Use it for start-up code where there is nothing to recover.
| Function | Purpose |
|---|---|
New(message, args...) |
create an error; args may include an ErrorCode, FieldErrors and errors to nest |
Wrap(err, message, args...) |
create an error that nests err |
NewWithError(err, format, args...) |
like Wrap, with the error first |
NewValidationError(message, fields...) |
create a 422 error with field errors |
Join(errs...) |
combine several errors |
As(err) |
get the *Error from any error chain |
Has(err, code, evalNested...) |
find an error with a given code |
Must(err) |
panic on error |
NewErrorCode(name, value) |
define a code |
E is an alias for *Error.
github.com/pixie-sh/errors-go/utils holds a few helpers used across Pixie services: Hash and HashCompare (bcrypt), Encrypt and Decrypt (AES-256), Md5, and Nil and IsPointer for interface checks.