feat(cookies,encoding): panic handling

This commit is contained in:
Gustavo "Guz" L. de Mello
2024-07-14 13:40:13 -03:00
parent 63d71cd625
commit 294b943353
2 changed files with 19 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ package cookies
import ( import (
e "errors" e "errors"
"fmt"
"math/bits" "math/bits"
"net/http" "net/http"
"reflect" "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) { func forEachField(v *reflect.Value, callback func(fv *reflect.Value, ft *reflect.StructField) error) (err error) {
t := v.Type() 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++ { for i := 0; i < t.NumField(); i++ {
ft := t.Field(i) ft := t.Field(i)
fv := v.FieldByName(ft.Name) fv := v.FieldByName(ft.Name)

View File

@@ -62,3 +62,15 @@ func TestUnmarshal(t *testing.T) {
t.Fatalf("Assertion failed, expected:\n%v\n\nfound:\n%v", TEST_VALUE, tc.TypedValue) 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)
}
}