Skip to content

Commit

Permalink
Merge pull request #134 from benmoss/fix-errors
Browse files Browse the repository at this point in the history
Fix how errors are printed
  • Loading branch information
k8s-ci-robot committed Apr 9, 2020
2 parents c87224d + 271ead0 commit 4cae117
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions klogr/klogr.go
Expand Up @@ -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)
}
Expand Down
29 changes: 29 additions & 0 deletions klogr/klogr_test.go
Expand Up @@ -2,7 +2,10 @@ package klogr

import (
"bytes"
"encoding/json"
"errors"
"flag"
"strings"
"testing"

"k8s.io/klog/v2"
Expand Down Expand Up @@ -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"
`,
},
}
Expand All @@ -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))
}

0 comments on commit 4cae117

Please sign in to comment.