From b7e9547d461965cd35e951299568bb40ef05d06b Mon Sep 17 00:00:00 2001 From: David Cai Date: Mon, 29 Jan 2018 11:36:38 +0800 Subject: [PATCH] feat: handle panic in Mask() --- jsonmask.go | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/jsonmask.go b/jsonmask.go index cda2bab..ca5ecb1 100644 --- a/jsonmask.go +++ b/jsonmask.go @@ -1,16 +1,35 @@ package jsonmask +import ( + "errors" +) + // Mask selects the specific parts of an object, according to the "mask". -func Mask(obj interface{}, mask string) (interface{}, error) { +func Mask(obj interface{}, mask string) (res interface{}, err error) { + defer func() { + if r := recover(); err != nil { + res = obj + + switch r.(type) { + case error: + err = r.(error) + case string: + err = errors.New(r.(string)) + default: + err = errors.New("json mask panic") + } + } + }() + compiledMask, err := compile(mask) if err != nil { return nil, err } - filteredObj, err := filter(obj, compiledMask) + res, err = filter(obj, compiledMask) if err != nil { return nil, err } - return filteredObj, nil + return res, nil }