3 `errwrap` is a package for Go that formalizes the pattern of wrapping errors
4 and checking if an error contains another error.
6 There is a common pattern in Go of taking a returned `error` value and
7 then wrapping it (such as with `fmt.Errorf`) before returning it. The problem
8 with this pattern is that you completely lose the original `error` structure.
10 Arguably the _correct_ approach is that you should make a custom structure
11 implementing the `error` interface, and have the original error as a field
12 on that structure, such [as this example](http://golang.org/pkg/os/#PathError).
13 This is a good approach, but you have to know the entire chain of possible
14 rewrapping that happens, when you might just care about one.
16 `errwrap` formalizes this pattern (it doesn't matter what approach you use
17 above) by giving a single interface for wrapping errors, checking if a specific
18 error is wrapped, and extracting that error.
20 ## Installation and Docs
22 Install using `go get github.com/hashicorp/errwrap`.
24 Full documentation is available at
25 http://godoc.org/github.com/hashicorp/errwrap
31 Below is a very basic example of its usage:
34 // A function that always returns an error, but wraps it, like a real
36 func tryOpen() error {
37 _, err := os.Open("/i/dont/exist")
39 return errwrap.Wrapf("Doesn't exist: {{err}}", err)
48 // We can use the Contains helpers to check if an error contains
49 // another error. It is safe to do this with a nil error, or with
50 // an error that doesn't even use the errwrap package.
51 if errwrap.Contains(err, "does not exist") {
54 if errwrap.ContainsType(err, new(os.PathError)) {
58 // Or we can use the associated `Get` functions to just extract
59 // a specific error. This would return nil if that specific error doesn't
61 perr := errwrap.GetType(err, new(os.PathError))
67 If you're already making custom types that properly wrap errors, then
68 you can get all the functionality of `errwraps.Contains` and such by
69 implementing the `Wrapper` interface with just one function. Example:
77 func (e *AppError) WrappedErrors() []error {
85 err := &AppError{Err: fmt.Errorf("an error")}
86 if errwrap.ContainsType(err, fmt.Errorf("")) {