feature (errors): add support fmt specifier with operands to WithMsg(...) (#2126)

This commit is contained in:
Jim authored and GitHub committed 2022-06-03 10:38:32 -04:00
1 parent 2a5aaea8b2
commit 6ceda0e595
3 files changed
+13 -3

No files matched your search

+1 -1
View File
@@ -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
+5 -2
View File
@@ -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
}
}
+7
View File
@@ -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)