diff options
-rw-r--r-- | securecookie.go | 31 | ||||
-rw-r--r-- | securecookie_test.go | 13 |
2 files changed, 42 insertions, 2 deletions
diff --git a/securecookie.go b/securecookie.go index 1c743fc..e997fbd 100644 --- a/securecookie.go +++ b/securecookie.go @@ -363,12 +363,15 @@ func CodecsFromPairs(keyPairs ...[]byte) []Codec { // key rotation. func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { + var errors MultiError for _, codec := range codecs { if encoded, err := codec.Encode(name, value); err == nil { return encoded, nil + } else { + errors = append(errors, err) } } - return "", errors.New("securecookie: the value could not be encoded") + return "", errors } // DecodeMulti decodes a cookie value using a group of codecs. @@ -377,10 +380,34 @@ func EncodeMulti(name string, value interface{}, // key rotation. func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { + var errors MultiError for _, codec := range codecs { if err := codec.Decode(name, value, dst); err == nil { return nil + } else { + errors = append(errors, err) } } - return errors.New("securecookie: the value could not be decoded") + return errors +} + +// MultiError groups multiple errors. +type MultiError []error + +func (m MultiError) Error() string { + s := "" + for k, v := range m { + if v != nil && k == 0 { + s = v.Error() + } + } + switch len(m) { + case 0: + return "(0 errors)" + case 1: + return s + case 2: + return s + " (and 1 other error)" + } + return fmt.Sprintf("%s (and %d other errors)", s, len(m)-1) } diff --git a/securecookie_test.go b/securecookie_test.go index 0187ba0..099c290 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -10,6 +10,7 @@ import ( "crypto/sha256" "errors" "fmt" + "strings" "testing" ) @@ -131,6 +132,18 @@ func TestEncoding(t *testing.T) { } } +func TestMultiError(t *testing.T) { + s1, s2 := New(nil, nil), New(nil, nil) + _, err := EncodeMulti("sid", "value", s1, s2) + if len(err.(MultiError)) != 2 { + t.Errorf("Expected 2 errors, got %s.", err) + } else { + if strings.Index(err.Error(), "hash key is not set") == -1 { + t.Errorf("Expected missing hash key error, got %s.", err.Error()) + } + } +} + // ---------------------------------------------------------------------------- type FooBar struct { |