diff --git a/internals/cookies/encoding.go b/internals/cookies/encoding.go index 47d3496..8335c3f 100644 --- a/internals/cookies/encoding.go +++ b/internals/cookies/encoding.go @@ -2,6 +2,7 @@ package cookies import ( e "errors" + "fmt" "math/bits" "net/http" "reflect" @@ -119,6 +120,12 @@ func Unmarshal[T any](data http.Cookie, v *TypedCookie[T]) error { func forEachField(v *reflect.Value, callback func(fv *reflect.Value, ft *reflect.StructField) error) (err error) { t := v.Type() + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("Panic while trying to loop through fields. Error:\n%v", r) + } + }() + for i := 0; i < t.NumField(); i++ { ft := t.Field(i) fv := v.FieldByName(ft.Name) diff --git a/internals/cookies/encoding_test.go b/internals/cookies/encoding_test.go index fe1e4f1..9798100 100644 --- a/internals/cookies/encoding_test.go +++ b/internals/cookies/encoding_test.go @@ -62,3 +62,15 @@ func TestUnmarshal(t *testing.T) { t.Fatalf("Assertion failed, expected:\n%v\n\nfound:\n%v", TEST_VALUE, tc.TypedValue) } } + +func TestPanicUnmarshal(t *testing.T) { + type Private struct { + //nolint:unused + privateField string `cookie:"private"` + } + var tc TypedCookie[Private] + err := Unmarshal(http.Cookie{Value: "private:Hello world"}, &tc) + if err == nil { + t.Fatalf("Function did not recover from panic, resulting value:\n%v", tc) + } +}