From 3b31fc3875132cf36ce6e058180932da829fafec Mon Sep 17 00:00:00 2001 From: Matthew Christopher Date: Sat, 22 Jul 2023 07:16:18 -0700 Subject: [PATCH] Prevent nil-dereference in format.Object for boxed nil error (#681) --- format/format.go | 2 +- format/format_test.go | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/format/format.go b/format/format.go index 4ffb04d1e..6c1680638 100644 --- a/format/format.go +++ b/format/format.go @@ -259,7 +259,7 @@ func Object(object interface{}, indentation uint) string { indent := strings.Repeat(Indent, int(indentation)) value := reflect.ValueOf(object) commonRepresentation := "" - if err, ok := object.(error); ok { + if err, ok := object.(error); ok && !isNilValue(value) { // isNilValue check needed here to avoid nil deref due to boxed nil commonRepresentation += "\n" + IndentString(err.Error(), indentation) + "\n" + indent } return fmt.Sprintf("%s<%s>: %s%s", indent, formatType(value), commonRepresentation, formatValue(value, indentation)) diff --git a/format/format_test.go b/format/format_test.go index 962e63943..bbb7fd7b9 100644 --- a/format/format_test.go +++ b/format/format_test.go @@ -7,6 +7,7 @@ import ( "time" . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" . "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" @@ -73,6 +74,16 @@ type NotCustomFormatted struct { Count int } +type CustomError struct { + Details string +} + +var _ error = &CustomError{} + +func (c *CustomError) Error() string { + return c.Details +} + func customFormatter(obj interface{}) (string, bool) { cf, ok := obj.(CustomFormatted) if !ok { @@ -626,6 +637,11 @@ var _ = Describe("Format", func() { \}, \}`)) }) + + It("should not panic if the error is a boxed nil", func() { + var err *CustomError + Expect(Object(err, 1)).Should(Equal(" <*format_test.CustomError | 0x0>: nil")) + }) }) })