From 22d978fe698535bc14085b58a70639de1f930760 Mon Sep 17 00:00:00 2001 From: Jan Semmelink <jan@uafrica.com> Date: Fri, 17 Sep 2021 14:13:24 +0200 Subject: [PATCH] Added readme and test for nexted Is() --- errors/README.md | 6 ++++++ errors/errors_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/errors/README.md b/errors/README.md index 9190b1e..39be72b 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 f9a8e2c..75bf7a3 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 +} -- GitLab