feat(cookies,encoding): panic handling
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user