Skip to content

Commit

Permalink
Recover from nil pointers when logging
Browse files Browse the repository at this point in the history
Signed-off-by: Davanum Srinivas <davanum@gmail.com>
  • Loading branch information
dims committed Dec 18, 2021
1 parent 9248e72 commit 115f500
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion klog.go
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,7 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
// (https://github.com/kubernetes/kubernetes/pull/106594#issuecomment-975526235).
switch v := v.(type) {
case fmt.Stringer:
writeStringValue(b, true, v.String())
writeStringValue(b, true, StringertoString(v))
case string:
writeStringValue(b, true, v)
case error:
Expand All @@ -872,6 +872,16 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
}
}

func StringertoString(s fmt.Stringer) (ret string) {
defer func() {
if err := recover(); err != nil {
ret = "nil"
}
}()
ret = s.String()
return ret
}

func writeStringValue(b *bytes.Buffer, quote bool, v string) {
data := []byte(v)
index := bytes.IndexByte(data, '\n')
Expand Down

0 comments on commit 115f500

Please sign in to comment.