diff --git a/securecookie.go b/securecookie.go index 4d5ea86..bc440b5 100644 --- a/securecookie.go +++ b/securecookie.go @@ -244,6 +244,14 @@ func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { return s } +// Err returns the deferred error stored on s during New or BlockFunc. It's +// the same error every subsequent Encode or Decode call would surface. This +// lets callers fail fast when configuration is wrong instead of waiting for +// the first cookie to be processed. +func (s *SecureCookie) Err() error { + return s.err +} + // Encode encodes a cookie value. // // It serializes, optionally encrypts, signs with a message authentication code, diff --git a/securecookie_test.go b/securecookie_test.go index 72905ae..3f3883d 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -88,6 +88,19 @@ func TestSecureCookieNilKey(t *testing.T) { } } +func TestErr(t *testing.T) { + if err := New([]byte("hashkey"), nil).Err(); err != nil { + t.Fatalf("expected nil Err for a valid hash key, got %v", err) + } + if err := New(nil, nil).Err(); err != errHashKeyNotSet { + t.Fatalf("expected errHashKeyNotSet from Err, got %v", err) + } + // Invalid block key (wrong size) is surfaced via BlockFunc. + if err := New([]byte("hashkey"), []byte{1, 2, 3}).Err(); err == nil { + t.Fatal("expected non-nil Err for an invalid block key") + } +} + func TestDecodeInvalid(t *testing.T) { // List of invalid cookies, which must not be accepted, base64-decoded // (they will be encoded before passing to Decode).