From 271ead0aefd1747c489a83171d77d5eef2723f15 Mon Sep 17 00:00:00 2001 From: Ben Moss Date: Wed, 8 Apr 2020 21:53:22 +0000 Subject: [PATCH] Fix how errors are printed --- klogr/klogr.go | 5 +++++ klogr/klogr_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/klogr/klogr.go b/klogr/klogr.go index 8e10665c..944cb70a 100644 --- a/klogr/klogr.go +++ b/klogr/klogr.go @@ -134,6 +134,11 @@ func flatten(kvList ...interface{}) string { } func pretty(value interface{}) string { + if err, ok := value.(error); ok { + if _, ok := value.(json.Marshaler); !ok { + value = err.Error() + } + } jb, _ := json.Marshal(value) return string(jb) } diff --git a/klogr/klogr_test.go b/klogr/klogr_test.go index ce59406b..795eefd1 100644 --- a/klogr/klogr_test.go +++ b/klogr/klogr_test.go @@ -2,7 +2,10 @@ package klogr import ( "bytes" + "encoding/json" + "errors" "flag" + "strings" "testing" "k8s.io/klog/v2" @@ -70,6 +73,20 @@ func TestInfo(t *testing.T) { text: "test", keysAndValues: []interface{}{"akey", "avalue", "akey2"}, expectedOutput: ` "msg"="test" "basekey1"="basevar1" "basekey2"=null "akey"="avalue" "akey2"=null +`, + }, + "should correctly print regular error types": { + klogr: New().V(0), + text: "test", + keysAndValues: []interface{}{"err", errors.New("whoops")}, + expectedOutput: ` "msg"="test" "err"="whoops" +`, + }, + "should use MarshalJSON if an error type implements it": { + klogr: New().V(0), + text: "test", + keysAndValues: []interface{}{"err", &customErrorJSON{"whoops"}}, + expectedOutput: ` "msg"="test" "err"="WHOOPS" `, }, } @@ -95,3 +112,15 @@ func TestInfo(t *testing.T) { }) } } + +type customErrorJSON struct { + s string +} + +func (e *customErrorJSON) Error() string { + return e.s +} + +func (e *customErrorJSON) MarshalJSON() ([]byte, error) { + return json.Marshal(strings.ToUpper(e.s)) +}