Skip to content

Repository files navigation

go-errors Travis Build BadgeGo Report Card BadgeGoDoc Badge

This package aims to provide flexible general-purpose error handling functionality, with the following specific features in mind:

  • Error wrapping: Allowing an error's cause to be preserved along with additional information.
  • Stack tracing: Allowing the path taken to return an error to be easily identified.
  • Structured fields: Allowing errors to be logged with additional contextual information.

This library has built upon the mistakes made and lessons learnt with regards to error handling at Icelolly whilst working on internal APIs. This library was inspired by approaches found elsewhere in the community, most notably the approach found in Upspin.

Usage

Creating and Wrapping Errors

Errors may have a few different pieces of information attached to them; an errors.Kind, a message, and fields. All of these things are optional, but at least an errors.Kindor message must be given if using errors.New. Along with this information, file and line information will be added automatically. If you're wrapping an error, the only thing you must pass is an error to wrap as the first argument:

constErrInvalidName errors.Kind="auth: user's name is invalid"funcpersistUser(user*User) error {
ifuser.Name=="" {
// Error kinds like `ErrInvalidName` can be used to react to different // errors to decide how to handle them at the caller.returnerrors.New(ErrInvalidName)
}
err:=persist(user)
iferr!=nil {
// Wrapping errors let's you add contextual information which may be// extracted again later (e.g. for logging).returnerrors.Wrap(err, "auth: failed to persist user in DB").
WithField("user", user)
}
returnnil
}

Handling Errors

Most error handling is done using errors.Is, which checks if the given error is of a given errors.Kind. If the error doesn't have it's own errors.Kind, then errors.Is will look through the errors stack until it finds an errors.Kind:

funcregisterUserHandler(w http.ResponseWriter, r*http.Request) {
user:=// ...err:=persistUser(user)
switch {
caseerrors.Is(err, ErrInvalidName):
http.Error(w, "user has invalid username", 400)
returncaseerr!=nil:
http.Error(w, http.StatusText(500), 500)
return
}
// ...
}

A more thorough example of usage can be found in the example/ directory. It showcases creating errors, wrapping them, handling different kinds of errors, and dealing with things like logging.

See More

About

Flexible, general-purpose error handling for Go.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages