Improved error handling

This commit is contained in:
Eduard Urbach 2023-07-06 17:26:19 +02:00
parent 9b9aef76eb
commit 0add931846
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 23 additions and 5 deletions

View File

@ -13,7 +13,7 @@ type Collection[T any] interface {
Clear() Clear()
Delete(key string) Delete(key string)
Exists(key string) bool Exists(key string) bool
Get(key string) (value *T, ok bool) Get(key string) (value *T, err error)
Set(key string, value *T) Set(key string, value *T)
} }
@ -67,9 +67,14 @@ func (c *collection[T]) All() <-chan *T {
} }
// Get returns the value for the given key. // 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) 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. // Set sets the value for the given key.

View File

@ -17,9 +17,9 @@ func TestCollectionGet(t *testing.T) {
defer users.Clear() defer users.Clear()
users.Set("1", &User{Name: "User 1"}) 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) assert.NotNil(t, user)
} }

13
Errors.go Normal file
View File

@ -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)
}