errors-go gives every Go error a code, an HTTP status, optional field errors and the errors it wraps. It marshals to JSON, and errors.Is and errors.As from the standard library keep working.
go get github.com/pixie-sh/errors-go
Go 1.23+. MIT licensed. The full reference is in the README.
Somewhere between the repository and the HTTP handler, someone has to decide whether an error is a 404, a 409 or a 500. With plain errors that decision ends up in string matching or a growing switch.
user, err := repo.Find(id)
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
http.Error(w, "not found", 404)
case strings.Contains(err.Error(), "duplicate"):
http.Error(w, "conflict", 409)
default:
http.Error(w, "internal error", 500)
}
return
}
Each handler repeats the mapping, and the client gets a bare string.
// where the error happens
return errors.New("user %s not found", id, errors.NotFoundErrorCode)
// one handler for every endpoint
func writeError(w http.ResponseWriter, err error) {
e, ok := errors.As(err)
if !ok {
e = errors.Wrap(err, "unexpected error")
}
w.WriteHeader(e.GetHTTPStatus())
json.NewEncoder(w).Encode(e)
}
The code travels with the error. The handler only reads it.
An error code is a name and a number. The last three digits are the HTTP status.
Wrapping keeps the original error and its code, through as many layers as you have.
The JSON form carries the code, the message, field errors and nested errors.
New takes a format string and its arguments. An ErrorCode, field errors and errors to nest can be mixed in at any position.
Define your own with NewErrorCode, or use the ones included for input, database, system and stream errors.
Wrap nests an error and inherits its code unless you set a new one. %w works in messages too.
*Error implements Unwrap and Is. Is matches by code across the whole nested tree.
NewValidationError returns a 422 with one entry per invalid field.
Join drops nils, returns nil when nothing is left, and keeps every error searchable.
In debug mode each error records its stack and caller. In production it stays small.
var OrderLockedErrorCode = errors.NewErrorCode("OrderLockedError", 40000+errors.HTTPConflict)
err := errors.New("order %d is locked", 7, OrderLockedErrorCode)
fmt.Println(err) // OrderLockedError-40409 order 7 is locked
fmt.Println(err.GetHTTPStatus()) // 409func findUser(id string) error {
return errors.New("user %s not found", id, errors.NotFoundErrorCode)
}
err := errors.Wrap(findUser("42"), "loading profile")
fmt.Println(err)
// NotFoundError-40404 loading profile; NotFoundError-40404 user 42 not found
fmt.Println(err.GetHTTPStatus()) // 404
// errors from other packages wrap the same way
err = errors.Wrap(io.ErrUnexpectedEOF, "reading body", errors.ErrorUnmarshallBodyErrorCode)
stderrors.Is(err, io.ErrUnexpectedEOF) // true// by code
if e, ok := errors.Has(err, errors.NotFoundErrorCode); ok {
// e is the *Error carrying that code
}
// with the standard library
notFound := errors.New("", errors.NotFoundErrorCode)
stderrors.Is(err, notFound) // true, matched by code
// get the structured error out of any chain
if e, ok := errors.As(err); ok {
fmt.Println(e.Code.Name, e.Code.Value) // NotFoundError 40404
}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"},
)
// err.GetHTTPStatus() == 422
// {
// "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" }
// ]
// }err := errors.Join(findUser("1"), nil, lockedErr)
_, found := errors.Has(err, OrderLockedErrorCode, true) // true
stderrors.Is(err, lockedErr) // true
errors.Join(nil, nil) == nil // trueb, _ := json.Marshal(errors.Wrap(findUser("42"), "loading profile"))
// {"code":"NotFoundError-40404","message":"loading profile",
// "nested_error":[{"code":"NotFoundError-40404","message":"user 42 not found"}]}
// and back, in the service that receives it
var back errors.Error
json.Unmarshal(b, &back)
back.GetHTTPStatus() // 404The number is the range plus the HTTP status, so NotFoundErrorCode is 40404.
| 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 |
These libraries run in our own services every day. Use one, or all of them.