Skip to content

Commit 2004d9d

Browse files
committed
update README with usage examples including standard error methods
1 parent a5e9814 commit 2004d9d

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

README.md

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@ be a list of errors. If the caller knows this, they can unwrap the
1414
list and access the errors. If the caller doesn't know, the error
1515
formats to a nice human-readable format.
1616

17-
`go-multierror` implements the
18-
[errwrap](https://github.com/hashicorp/errwrap) interface so that it can
19-
be used with that library, as well.
17+
`go-multierror` is fully compatible with the Go standard library
18+
[errors](https://golang.org/pkg/errors/) package, including the
19+
functions `As`, `Is`, and `Unwrap`. This provides a standardized approach
20+
for introspecting on error values.
2021

2122
## Installation and Docs
2223

@@ -81,6 +82,39 @@ if err := something(); err != nil {
8182
}
8283
```
8384

85+
You can also use the standard [`errors.Unwrap`](https://golang.org/pkg/errors/#Unwrap)
86+
function. This will continue to unwrap into subsequent errors until none exist.
87+
88+
**Extracting an error**
89+
90+
The standard library [`errors.As`](https://golang.org/pkg/errors/#As)
91+
function can be used directly with a multierror to extract a specific error:
92+
93+
```go
94+
// Assume err is a multierror value
95+
err := somefunc()
96+
97+
// We want to know if "err" has a "RichErrorType" in it and extract it.
98+
var errRich RichErrorType
99+
if errors.As(err, &errRich) {
100+
// It has it, and now errRich is populated.
101+
}
102+
```
103+
104+
**Checking for an exact error value**
105+
106+
Some errors are returned as exact errors such as the [`ErrNotExist`](https://golang.org/pkg/os/#pkg-variables)
107+
error in the `os` package. You can check if this error is present by using
108+
the standard [`errors.Is`](https://golang.org/pkg/errors/#Is) function.
109+
110+
```go
111+
// Assume err is a multierror value
112+
err := somefunc()
113+
if errors.Is(err, os.ErrNotExist) {
114+
// err contains os.ErrNotExist
115+
}
116+
```
117+
84118
**Returning a multierror only if there are errors**
85119

86120
If you build a `multierror.Error`, you can use the `ErrorOrNil` function

0 commit comments

Comments
 (0)