diff options
author | Jonathan Amsterdam <jba@google.com> | 2019-08-02 06:43:20 -0400 |
---|---|---|
committer | Jonathan Amsterdam <jba@google.com> | 2019-08-06 11:13:05 +0000 |
commit | 546ea78efa159680dde0df42f1f2091ccafef4df (patch) | |
tree | 6a6651d24b88ee567f02a26196feda32f99a396d /src/errors/errors.go | |
parent | a4c825156d0a3817377a2b7e5b30ab50e11440ab (diff) | |
download | go-git-546ea78efa159680dde0df42f1f2091ccafef4df.tar.gz |
errors: improve doc
Explain wrapping and how to use Is and As in the package doc.
Explain "chain" in Is and As.
Updates #33364.
Change-Id: Ic06362106dbd129e33dd47e63176ee5355492086
Reviewed-on: https://go-review.googlesource.com/c/go/+/188737
Reviewed-by: Rob Pike <r@golang.org>
Diffstat (limited to 'src/errors/errors.go')
-rw-r--r-- | src/errors/errors.go | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/errors/errors.go b/src/errors/errors.go index b8a46921be..85d4260762 100644 --- a/src/errors/errors.go +++ b/src/errors/errors.go @@ -3,9 +3,58 @@ // license that can be found in the LICENSE file. // Package errors implements functions to manipulate errors. +// +// The New function creates errors whose only content is a text message. +// +// The Unwrap, Is and As functions work on errors that may wrap other errors. +// An error wraps another error if its type has the method +// +// Unwrap() error +// +// If e.Unwrap() returns a non-nil error w, then we say that e wraps w. +// +// A simple way to create wrapped errors is to call fmt.Errorf and apply the %w verb +// to the error argument: +// +// fmt.Errorf("... %w ...", ..., err, ...).Unwrap() +// +// returns err. +// +// Unwrap unpacks wrapped errors. If its argument's type has an +// Unwrap method, it calls the method once. Otherwise, it returns nil. +// +// Is unwraps its first argument sequentially looking for an error that matches the +// second. It reports whether it finds a match. It should be used in preference to +// simple equality checks: +// +// if errors.Is(err, os.ErrExist) +// +// is preferable to +// +// if err == os.ErrExist +// +// because the former will succeed if err wraps os.ErrExist. +// +// As unwraps its first argument sequentially looking for an error that can be +// assigned to its second argument, which must be a pointer. If it succeeds, it +// performs the assignment and returns true. Otherwise, it returns false. The form +// +// var perr *os.PathError +// if errors.As(err, &perr) { +// fmt.Println(perr.Path) +// } +// +// is preferable to +// +// if perr, ok := err.(*os.PathError); ok { +// fmt.Println(perr.Path) +// } +// +// because the former will succeed if err wraps an *os.PathError. package errors // New returns an error that formats as the given text. +// Each call to New returns a distinct error value even if the text is identical. func New(text string) error { return &errorString{text} } |