[英]Redis doesn't return WRONGTYPE as an error in a transaction
抱歉,如果這已經被問到了。 首先,讓我展示如何重現我的問題:
> SET test 10
func main() {
redisClient := getConnection() // Abstracting get connection for simplicity
r, err := redisClient.Do("HSET", "test", "f1", "v1", "f2", "v2")
fmt.Printf("%+v e: %+v\n")
}
很公平,在這一步中顯示了以下錯誤(這意味着err != nil
):
WRONGTYPE Operation against a key holding the wrong kind of value e: WRONGTYPE Operation against a key holding the wrong kind of value
func main() {
redisClient := getConnection()
redisClient.Send("MULTI")
redisClient.Send("HSET", "test", "f1", "v1", "f2", "v2")
r, err := redisClient.Do("EXEC")
fmt.Printf("%+v e: %+v\n")
}
正在打印的行是:
WRONGTYPE Operation against a key holding the wrong kind of value e: <nil>
這對我來說似乎不一致,因為我希望MULTI
也會在錯誤變量中返回WRONGTYPE
。
這是預期的行為還是我錯過了什么?
Redis 事務中的每個命令都有兩個結果。 一種是將命令添加到事務中的結果,另一種是在事務中執行命令的結果。
Do
方法返回將命令添加到事務的結果。
Redis EXEC命令返回一個數組,其中每個元素都是在事務中執行命令的結果。 檢查每個元素以檢查單個命令錯誤:
values, err := redis.Values(redisClient.Do("EXEC"))
if err != nil {
// Handle error
}
if err, ok := values[0].(redis.Error); ok {
// Handle error for command 0.
// Adjust the index to match the actual index of
// of the HMSET command in the transaction.
}
用於測試事務命令錯誤的助手 function 可能有用:
func execValues(reply interface{}, err error) ([]interface{}, error) {
if err != nil {
return nil, err
}
values, ok := reply.([]interface{})
if !ok {
return nil, fmt.Errorf("unexpected type for EXEC reply, got type %T", reply)
}
for _, v := range values {
if err, ok := v.(redis.Error); ok {
return values, err
}
}
return values, nil
}
像這樣使用它:
values, err := execValues(redisClient.Do("EXEC"))
if err != nil {
// Handle error.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.