mirror of
https://github.com/tailscale/tailscale.git
synced 2025-03-27 19:43:01 +00:00
util/vizerror: add Wrapf function that combines Errorf with Wrap
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>
This commit is contained in:
parent
8b1e7f646e
commit
414b5b8402
@ -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)
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user