merr: implement WithKV

This commit is contained in:
Brian Picciano 2019-02-02 20:18:39 -05:00
parent 526639041b
commit c6e29715b0
2 changed files with 35 additions and 0 deletions

View File

@ -101,3 +101,20 @@ func KV(e error) KVer {
return KVer{kvm}
}
type kvKey string
// WithKV embeds key/value pairs into an error, just like WithValue, but it does
// so via one or more passed in maps
func WithKV(e error, kvMaps ...map[string]interface{}) error {
if e == nil {
return nil
}
er := wrap(e, true, 1)
for _, kvMap := range kvMaps {
for k, v := range kvMap {
er.attr[kvKey(k)] = val{val: v, visible: true}
}
}
return er
}

View File

@ -77,4 +77,22 @@ func TestKV(t *T) {
),
"kv: %#v", kv,
))
er = WithKV(er, map[string]interface{}{"D": 4, "k": 5})
kv = KV(er).KV()
massert.Fatal(t, massert.Comment(
massert.All(
massert.Len(kv, 8),
massert.Equal("foo", kv["err"]),
massert.Equal("baz", kv["bar"]),
massert.Equal(true,
strings.HasPrefix(kv["errSrc"].(string), "merr/kv_test.go:")),
massert.Equal("1", kv["merr.A(k)"]),
massert.Equal("2", kv["merr.B(k)"]),
massert.Equal("3", kv["merr.C(k)"]),
massert.Equal(4, kv["D"]),
massert.Equal(5, kv["merr.kvKey(k)"]),
),
"kv: %#v", kv,
))
}