From 6ceda0e595eb10869091fc0c115954d16cfdb158 Mon Sep 17 00:00:00 2001 From: Jim Date: Fri, 3 Jun 2022 10:38:32 -0400 Subject: [PATCH] feature (errors): add support fmt specifier with operands to WithMsg(...) (#2126) --- internal/errors/error.go | 2 +- internal/errors/option.go | 7 +++++-- internal/errors/option_test.go | 7 +++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/internal/errors/error.go b/internal/errors/error.go index 72494c72da..d505210d80 100644 --- a/internal/errors/error.go +++ b/internal/errors/error.go @@ -74,7 +74,7 @@ func E(ctx context.Context, opt ...Option) error { Code: code, Op: opts.withOp, Wrapped: opts.withErrWrapped, - Msg: opts.withErrMsg, + Msg: fmt.Sprintf(opts.withErrMsg, opts.withErrMsgArgs...), } if opts.withoutEvent { return err diff --git a/internal/errors/option.go b/internal/errors/option.go index 89bc577ab6..1b70ba9f8a 100644 --- a/internal/errors/option.go +++ b/internal/errors/option.go @@ -17,6 +17,7 @@ type Options struct { withCode Code withErrWrapped error withErrMsg string + withErrMsgArgs []any withOp Op withoutEvent bool } @@ -34,10 +35,12 @@ func WithWrap(e error) Option { } // WithMsg provides an option to provide a message when creating a new -// error. -func WithMsg(msg string) Option { +// error. If args are provided, the the msg string is used as a fmt specifier +// for the arguments and the resulting string is used as the msg. +func WithMsg(msg string, args ...any) Option { return func(o *Options) { o.withErrMsg = msg + o.withErrMsgArgs = args } } diff --git a/internal/errors/option_test.go b/internal/errors/option_test.go index 3d7a0ac7eb..88912a408a 100644 --- a/internal/errors/option_test.go +++ b/internal/errors/option_test.go @@ -22,6 +22,13 @@ func Test_getOpts(t *testing.T) { opts = GetOpts(WithMsg("test msg")) testOpts.withErrMsg = "test msg" assert.Equal(opts, testOpts) + + opts = GetOpts(WithMsg("%s msg", "test")) + testOpts.withErrMsg = "%s msg" + testOpts.withErrMsgArgs = []any{"test"} + assert.Equal(opts, testOpts) + + assert.Equal("#1 test msg: unknown: error #0", E(context.Background(), WithMsg("#%d %s msg", 1, "test")).Error()) }) t.Run("WithWrap", func(t *testing.T) { assert := assert.New(t)