mediocregopher / radix.v2

Redis client for Go
http://godoc.org/github.com/mediocregopher/radix.v2
MIT License
433 stars 92 forks source link

Returning "wrong type" while key does not exist #60

Closed tsirolnik closed 7 years ago

tsirolnik commented 7 years ago

Having the following case -

    redisClient, err := redisPool.Get()
    ....
    defer redisPool.Put(redisClient)
    redisResp := redisClient.Cmd("GET", "someKey")
    respErr := redisResp.Err 
    strValue, strErr := redisResp.Str()

If someKey is non-existent, then the value of respErr will be "wrong type" (probably due to receiving nil).

I think that we should either get an empty string as strValue's value, respErr with "key value non-existing" or strErr with the value of "empty value received". Another option is to have a default value.

Many times non-existing key isn't necessarily a case of an error.

mediocregopher commented 7 years ago

Hey there! What's happening is that redis considers nil and strings to be two different types, so when you call Str on a response but that response is a nil it is technically the wrong type. I'd prefer to keep those strict semantics rather than do fuzzy casting to avoid confusion.

An easy way to get around the problem you're having (you want nil returns to be empty strings) is to do something like this:

resp := redisClient.Cmd("GET", "someKey")
// If there's an error on the resp that means it's some kind of network error or "key wrong type"
// or something immediate like that
if err := resp.Err; err != nil {
    return err
}

// If the resp isn't an error itself then you don't have to worry about checking the casting error,
// since you can be sure you know what the possible types GET returns are
strValue, _ := resp.Str()

Hope this helps, let me know if you have any further questions though.