Skip to content

Commit

Permalink
Merge pull request #15 from fastbill/improve-error-handlling-cache
Browse files Browse the repository at this point in the history
Implement ErrNotFound in cache.Cache#GetJSON()
  • Loading branch information
perajovic authored Feb 5, 2020
2 parents 078b352 + 7e54d4f commit 66fa862
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ func (r *RedisClient) GetBool(key string) (bool, error) {
result, err := r.Get(key)
if err == redis.Nil {
return false, ErrNotFound
} else if err != nil {
return false, err
}

return strconv.ParseBool(result)
}

Expand All @@ -109,9 +112,12 @@ func (r *RedisClient) SetJSON(key string, value interface{}, expiration time.Dur
// If the client was set up with a prefix it will be added in front of the key.
func (r *RedisClient) GetJSON(key string, result interface{}) error {
resultStr, err := r.Get(key)
if err != nil {
if err == redis.Nil {
return ErrNotFound
} else if err != nil {
return err
}

return json.Unmarshal([]byte(resultStr), &result)
}

Expand Down
15 changes: 15 additions & 0 deletions cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ func TestGetBool(t *testing.T) {
assert.Error(t, err)
})
})

t.Run("value not found", func(t *testing.T) {
withRedis(t, func(redis *miniredis.Miniredis, client *RedisClient) {
_, err := client.GetBool("someKey")
assert.Equal(t, ErrNotFound, err)
})
})
}

func TestSetJSON(t *testing.T) {
Expand Down Expand Up @@ -178,6 +185,14 @@ func TestGetJSON(t *testing.T) {
assert.Error(t, err)
})
})

t.Run("value not found", func(t *testing.T) {
withRedis(t, func(redis *miniredis.Miniredis, client *RedisClient) {
result := &testStruct{}
err := client.GetJSON("foo", result)
assert.Equal(t, ErrNotFound, err)
})
})
}

func TestDel(t *testing.T) {
Expand Down

0 comments on commit 66fa862

Please sign in to comment.