diff --git a/errors/README.md b/errors/README.md index 9190b1e79b386bcee87209553f6ac1a55e2eaa17..39be72b24bf0f1464c62081225b1162586410219 100644 --- a/errors/README.md +++ b/errors/README.md @@ -175,3 +175,9 @@ This function can be used also for logging to determine the caller from the runt ## func Stack() This function is similar to Caller() but reports an array of callers, not only one. + +## func Is() + +You can compare a message with errors.Is() to some error specification. +It will look at the error or any cause to match the spec. +The spec is the error message. \ No newline at end of file diff --git a/errors/errors_test.go b/errors/errors_test.go index f9a8e2c6bce0d2cd2325d90fa5316cf7ab9d2f68..75bf7a3e85ee6666663530fa8f31d6b7d2a94a51 100644 --- a/errors/errors_test.go +++ b/errors/errors_test.go @@ -109,6 +109,23 @@ func TestIs(t *testing.T) { t.Logf("n=%d worked", n) } } + + //same but err is wrapped deeper + for n := 0; n <= 4; n++ { + if err := UserExists(n); err != nil { + switch { + case errors.Is(err, errNotFound): + t.Logf("u=%d failed with NOT FOUND", n) + case errors.Is(err, errDisabled): + t.Logf("u=%d failed because disabled", n) + default: + t.Logf("u=%d failed for unknown cause: %+v", n, err) + } + } else { + t.Logf("u=%d worked", n) + } + } + } var ( @@ -130,3 +147,10 @@ func ReadDb(x int) error { return errors.Errorf("invalid x=%d", x) } } + +func UserExists(u int) error { + if err := ReadDb(u); err != nil { + return errors.Wrapf(err, "cannot read user %d", u) + } + return nil +}