Improved error handling
This commit is contained in:
parent
9b9aef76eb
commit
0add931846
@ -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.
|
||||
|
@ -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)
|
||||
}
|
||||
|
||||
|
13
Errors.go
Normal file
13
Errors.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user