Skip to content

Commit

Permalink
Prevent nil-dereference in format.Object for boxed nil error (#681)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthchr committed Jul 22, 2023
1 parent 360849b commit 3b31fc3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion format/format.go
Expand Up @@ -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))
Expand Down
16 changes: 16 additions & 0 deletions format/format_test.go
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"))
})
})
})

Expand Down

0 comments on commit 3b31fc3

Please sign in to comment.