From 0add931846c20128f3137d67f44905079d19fe3f Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Thu, 6 Jul 2023 17:26:19 +0200 Subject: [PATCH] Improved error handling --- Collection.go | 11 ++++++++--- Collection_test.go | 4 ++-- Errors.go | 13 +++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 Errors.go diff --git a/Collection.go b/Collection.go index 45ea631..e81befb 100644 --- a/Collection.go +++ b/Collection.go @@ -13,7 +13,7 @@ type Collection[T any] interface { Clear() Delete(key string) Exists(key string) bool - Get(key string) (value *T, ok bool) + Get(key string) (value *T, err error) Set(key string, value *T) } @@ -67,9 +67,14 @@ func (c *collection[T]) All() <-chan *T { } // Get returns the value for the given key. -func (c *collection[T]) Get(key string) (*T, bool) { +func (c *collection[T]) Get(key string) (*T, error) { value, exists := c.data.Load(key) - return value.(*T), exists + + if !exists { + return nil, &KeyNotFoundError{Key: key} + } + + return value.(*T), nil } // Set sets the value for the given key. diff --git a/Collection_test.go b/Collection_test.go index 3e1637a..a1258b4 100644 --- a/Collection_test.go +++ b/Collection_test.go @@ -17,9 +17,9 @@ func TestCollectionGet(t *testing.T) { defer users.Clear() users.Set("1", &User{Name: "User 1"}) - user, exists := users.Get("1") + user, err := users.Get("1") - assert.True(t, exists) + assert.Nil(t, err) assert.NotNil(t, user) } diff --git a/Errors.go b/Errors.go new file mode 100644 index 0000000..5c00587 --- /dev/null +++ b/Errors.go @@ -0,0 +1,13 @@ +package ocean + +import "fmt" + +// KeyNotFoundError represents errors for cases where the requested key could not be found. +type KeyNotFoundError struct { + Key string +} + +// Error returns the error message. +func (e *KeyNotFoundError) Error() string { + return fmt.Sprintf("Key not found: %s", e.Key) +}