From 84998361337f650ee889fe2683bb69cddb58f538 Mon Sep 17 00:00:00 2001 From: Waldemar Quevedo Date: Thu, 17 Nov 2022 13:33:30 -0800 Subject: [PATCH] Add ErrKeyExists that is compatible with errors.Is on kv.Create (#1136) * Add ErrKeyExists error that is compatible with errors.Is on kv.Create Signed-off-by: Waldemar Quevedo --- jserrors.go | 2 ++ kv.go | 12 +++++++----- kv_test.go | 27 ++++++++++++++++++++++++++- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/jserrors.go b/jserrors.go index 41b50f0b8..8b97e86ce 100644 --- a/jserrors.go +++ b/jserrors.go @@ -123,6 +123,8 @@ const ( JSErrCodeMessageNotFound ErrorCode = 10037 JSErrCodeBadRequest ErrorCode = 10003 + + JSErrCodeStreamWrongLastSequence ErrorCode = 10071 ) // APIError is included in all API responses if there was an error. diff --git a/kv.go b/kv.go index defe68c82..7fb2e5dc2 100644 --- a/kv.go +++ b/kv.go @@ -297,7 +297,10 @@ var ( ErrKeyDeleted = errors.New("nats: key was deleted") ErrHistoryToLarge = errors.New("nats: history limited to a max of 64") ErrNoKeysFound = errors.New("nats: no keys found") - ErrKeyExists = errors.New("nats: key exists") +) + +var ( + ErrKeyExists JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamWrongLastSequence, Code: 400}, message: "key exists"} ) const ( @@ -632,10 +635,9 @@ func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) { // Check if the expected last subject sequence is not zero which implies // the key already exists. - if aerr, ok := err.(*APIError); ok { - if aerr.ErrorCode == 10071 { - return 0, ErrKeyExists - } + if errors.Is(err, ErrKeyExists) { + jserr := ErrKeyExists.(*jsError) + return 0, fmt.Errorf("%w: %s", err, jserr.message) } return 0, err diff --git a/kv_test.go b/kv_test.go index d2c386348..0eb96cbdb 100644 --- a/kv_test.go +++ b/kv_test.go @@ -14,6 +14,7 @@ package nats import ( + "errors" "fmt" "testing" "time" @@ -222,7 +223,31 @@ func TestKeyValueCreate(t *testing.T) { } _, err = kv.Create("key", []byte("1")) - if err != ErrKeyExists { + expected := "nats: wrong last sequence: 1: key exists" + if err.Error() != expected { + t.Fatalf("Expected %q, got: %v", expected, err) + } + if !errors.Is(err, ErrKeyExists) { t.Fatalf("Expected ErrKeyExists, got: %v", err) } + aerr := &APIError{} + if !errors.As(err, &aerr) { + t.Fatalf("Expected APIError, got: %v", err) + } + if aerr.Description != "wrong last sequence: 1" { + t.Fatalf("Unexpected APIError message, got: %v", aerr.Description) + } + if aerr.ErrorCode != 10071 { + t.Fatalf("Unexpected error code, got: %v", aerr.ErrorCode) + } + if aerr.Code != ErrKeyExists.APIError().Code { + t.Fatalf("Unexpected error code, got: %v", aerr.Code) + } + var kerr JetStreamError + if !errors.As(err, &kerr) { + t.Fatalf("Expected KeyValueError, got: %v", err) + } + if kerr.APIError().ErrorCode != 10071 { + t.Fatalf("Unexpected error code, got: %v", kerr.APIError().ErrorCode) + } }