Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a recovering decode hook #305

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions decode_hooks.go
Expand Up @@ -99,6 +99,19 @@ func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc {
}
}

// RecoveringDecodeHookFunc executes the input hook function and turns a panic into an error.
func RecoveringDecodeHookFunc(hook DecodeHookFunc) DecodeHookFunc {
return func(from, to reflect.Value) (v interface{}, err error) {
defer func() {
if r := recover(); r != nil {
v = nil
err = fmt.Errorf("internal error while parsing: %s", r)
}
}()
return DecodeHookExec(hook, from, to)
}
}

// StringToSliceHookFunc returns a DecodeHookFunc that converts
// string to []string by splitting on the given sep.
func StringToSliceHookFunc(sep string) DecodeHookFunc {
Expand Down
61 changes: 61 additions & 0 deletions decode_hooks_test.go
Expand Up @@ -204,6 +204,67 @@ func TestComposeDecodeHookFunc_safe_nofuncs(t *testing.T) {
}
}

func TestRecoveringDecodeHook(t *testing.T) {
f1 := func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
return data.(string) + "bar", nil
}
f := RecoveringDecodeHookFunc(f1)

result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "bar" {
t.Fatalf("bad: %#v", result)
}
}

func TestRecoveringDecodeHook_err(t *testing.T) {
f1 := func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() == reflect.String {
panic(errors.New("noooo"))
}
return data, nil
}
f := RecoveringDecodeHookFunc(f1)

type myStruct struct {
A string
B string
}
src := map[string]string{
"A": "one",
"B": "two",
}
dst := &myStruct{}
dConf := &DecoderConfig{
Result: dst,
ErrorUnused: true,
DecodeHook: f,
}
d, err := NewDecoder(dConf)
if err != nil {
t.Fatal(err)
}
err = d.Decode(src)
if err == nil {
t.Fatalf("bad: should return an error")
}
if err.Error() != `2 error(s) decoding:

* error decoding 'A': internal error while parsing: noooo
* error decoding 'B': internal error while parsing: noooo` {
t.Fatalf("bad: %s", err)
}
}

func TestStringToSliceHookFunc(t *testing.T) {
f := StringToSliceHookFunc(",")

Expand Down