summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorPercy Wegmann <percy@tailscale.com>2025-03-14 09:02:36 -0500
committerPercy Wegmann <percy@tailscale.com>2025-03-14 09:02:36 -0500
commit414b5b84026d6741a174d3993de9cd4ea5e279a6 (patch)
treeee268340993134449b50101ff337953301a2a921
parent8b1e7f646ee4730ad06c9b70c13e7861b964949b (diff)
downloadtailscale-percy/corp27066-vizerror-wrapf.tar.xz
tailscale-percy/corp27066-vizerror-wrapf.zip
util/vizerror: add Wrapf function that combines Errorf with Wrappercy/corp27066-vizerror-wrapf
This makes it convenient to wrap an error with a vizerror that needs to use a format string. Updates tailscale/corp#27066 Signed-off-by: Percy Wegmann <percy@tailscale.com>
-rw-r--r--util/vizerror/vizerror.go12
-rw-r--r--util/vizerror/vizerror_test.go11
2 files changed, 23 insertions, 0 deletions
diff --git a/util/vizerror/vizerror.go b/util/vizerror/vizerror.go
index 919d765d0..f294ef424 100644
--- a/util/vizerror/vizerror.go
+++ b/util/vizerror/vizerror.go
@@ -75,6 +75,18 @@ func WrapWithMessage(wrapped error, publicMsg string) error {
}
}
+// Wrapf wraps the given error with a Vizerror built using the specified publicMsgFormat and values.
+// It always returns a vizerror.Error.
+//
+// Warning: avoid using an error as one of the format arguments, as this will cause the text
+// of that error to be displayed to the end user (which is probably not what you want).
+func Wrapf(wrapped error, publicMsgFormat string, a ...any) error {
+ return Error{
+ publicErr: fmt.Errorf(publicMsgFormat, a...),
+ wrapped: wrapped,
+ }
+}
+
// As returns the first vizerror.Error in err's chain.
func As(err error) (e Error, ok bool) {
ok = errors.As(err, &e)
diff --git a/util/vizerror/vizerror_test.go b/util/vizerror/vizerror_test.go
index 242ca6462..f2538c64c 100644
--- a/util/vizerror/vizerror_test.go
+++ b/util/vizerror/vizerror_test.go
@@ -64,3 +64,14 @@ func TestWrapWithMessage(t *testing.T) {
t.Errorf("Unwrap = %q, want %q", errors.Unwrap(err), wrapped)
}
}
+
+func TestWrapf(t *testing.T) {
+ wrapped := errors.New("wrapped")
+ err := Wrapf(wrapped, "safe: %s", "for sure")
+ if err.Error() != "safe: for sure" {
+ t.Errorf(`Wrapf(wrapped, "safe: for sure").Error() = %q, want %q`, err.Error(), "safe: for sure")
+ }
+ if errors.Unwrap(err) != wrapped {
+ t.Errorf("Unwrap = %q, want %q", errors.Unwrap(err), wrapped)
+ }
+}