errors.New, errors.Is, errors.Join, errors.Unwrap
func New(text string) error
func Is(err, target error) bool
func Join(errs ...error) error
func Unwrap(err error) errorBuild sentinels, join several errors, and test membership in the tree. Unwrap does not unwrap a Join error.
| Parameter | Description |
|---|---|
text | The message stored by New. Each call returns a distinct value, even when the text is the same. |
err, target | Is walks the tree of err looking for a match with target. A nil err is not a match. |
errs | Join discards nil arguments and returns nil if every argument is nil. |
Returns: New and Join return an error, or nil for Join when nothing remains. Is returns whether a match was found. Unwrap returns the next error, or nil when there is no Unwrap() error method.
- Wrapping a single error with fmt.Errorf and %w is documented on the fmt page. Is walks that chain as well as a Join tree.
- The joined Error() text was measured on Go 1.24.0 as the two messages with a newline between them.
package main
import (
"errors"
"fmt"
)
func main() {
one := errors.New("one")
two := errors.New("two")
joined := errors.Join(one, two)
fmt.Println(joined)
fmt.Println(errors.Is(joined, one), errors.Is(joined, two))
fmt.Println(errors.Is(joined, errors.New("one")))
fmt.Println(errors.Unwrap(joined) == nil)
fmt.Println(errors.Join(nil, nil) == nil)
}Expected output
one
two
true true
false
true
trueRelated: fmt.Errorf, os.ErrNotExist and errors.Is