Skip to content

Commit 3b31fc3

Browse files
authored
Prevent nil-dereference in format.Object for boxed nil error (#681)
1 parent 360849b commit 3b31fc3

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

format/format.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ func Object(object interface{}, indentation uint) string {
259259
indent := strings.Repeat(Indent, int(indentation))
260260
value := reflect.ValueOf(object)
261261
commonRepresentation := ""
262-
if err, ok := object.(error); ok {
262+
if err, ok := object.(error); ok && !isNilValue(value) { // isNilValue check needed here to avoid nil deref due to boxed nil
263263
commonRepresentation += "\n" + IndentString(err.Error(), indentation) + "\n" + indent
264264
}
265265
return fmt.Sprintf("%s<%s>: %s%s", indent, formatType(value), commonRepresentation, formatValue(value, indentation))

format/format_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"time"
88

99
. "github.com/onsi/ginkgo/v2"
10+
1011
. "github.com/onsi/gomega"
1112
. "github.com/onsi/gomega/format"
1213
"github.com/onsi/gomega/types"
@@ -73,6 +74,16 @@ type NotCustomFormatted struct {
7374
Count int
7475
}
7576

77+
type CustomError struct {
78+
Details string
79+
}
80+
81+
var _ error = &CustomError{}
82+
83+
func (c *CustomError) Error() string {
84+
return c.Details
85+
}
86+
7687
func customFormatter(obj interface{}) (string, bool) {
7788
cf, ok := obj.(CustomFormatted)
7889
if !ok {
@@ -626,6 +637,11 @@ var _ = Describe("Format", func() {
626637
\},
627638
\}`))
628639
})
640+
641+
It("should not panic if the error is a boxed nil", func() {
642+
var err *CustomError
643+
Expect(Object(err, 1)).Should(Equal(" <*format_test.CustomError | 0x0>: nil"))
644+
})
629645
})
630646
})
631647

0 commit comments

Comments
 (0)