Skip to content

Commit

Permalink
Wrap ErrKeyExists on kv.Create WrongLastSequence error
Browse files Browse the repository at this point in the history
Signed-off-by: Waldemar Quevedo <wally@nats.io>
  • Loading branch information
wallyqs committed Nov 17, 2022
1 parent b5215a7 commit b763e76
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
2 changes: 1 addition & 1 deletion jserrors.go
Expand Up @@ -124,7 +124,7 @@ const (

JSErrCodeBadRequest ErrorCode = 10003

JSErrStreamWrongLastSequence ErrorCode = 10071
JSErrCodeStreamWrongLastSequence ErrorCode = 10071
)

// APIError is included in all API responses if there was an error.
Expand Down
13 changes: 8 additions & 5 deletions kv.go
Expand Up @@ -299,12 +299,8 @@ var (
ErrNoKeysFound = errors.New("nats: no keys found")
)

// KeyValueError is an error result for KeyValue operations which internally
// are JetStreamError as well so this is just an alias.
type KeyValueError = JetStreamError

var (
ErrKeyExists KeyValueError = &jsError{apiErr: &APIError{ErrorCode: JSErrStreamWrongLastSequence, Description: "key exists", Code: 400}}
ErrKeyExists JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamWrongLastSequence, Code: 400}, message: "key exists"}
)

const (
Expand Down Expand Up @@ -637,6 +633,13 @@ func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) {
return kv.Update(key, value, e.Revision())
}

// Check if the expected last subject sequence is not zero which implies
// the key already exists.
var aerr *APIError
if errors.Is(err, ErrKeyExists) && errors.As(err, &aerr) {
return 0, fmt.Errorf("%w: %s", ErrKeyExists, aerr.Description)
}

return 0, err
}

Expand Down
4 changes: 2 additions & 2 deletions kv_test.go
Expand Up @@ -223,7 +223,7 @@ func TestKeyValueCreate(t *testing.T) {
}

_, err = kv.Create("key", []byte("1"))
expected := "nats: wrong last sequence: 1"
expected := "nats: key exists: wrong last sequence: 1"
if err.Error() != expected {
t.Fatalf("Expected %q, got: %v", expected, err)
}
Expand All @@ -240,7 +240,7 @@ func TestKeyValueCreate(t *testing.T) {
if aerr.Code != ErrKeyExists.APIError().Code {
t.Fatalf("Unexpected error code, got: %v", aerr.Code)
}
var kerr KeyValueError
var kerr JetStreamError
if !errors.As(err, &kerr) {
t.Fatalf("Expected KeyValueError, got: %v", err)
}
Expand Down

0 comments on commit b763e76

Please sign in to comment.