From c6e29715b0ceb97da0f7062b2205088003980bc2 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 2 Feb 2019 20:18:39 -0500 Subject: [PATCH] merr: implement WithKV --- merr/kv.go | 17 +++++++++++++++++ merr/kv_test.go | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/merr/kv.go b/merr/kv.go index 030b24a..a5ec63f 100644 --- a/merr/kv.go +++ b/merr/kv.go @@ -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 +} diff --git a/merr/kv_test.go b/merr/kv_test.go index dc1f107..7738598 100644 --- a/merr/kv_test.go +++ b/merr/kv_test.go @@ -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, + )) }