Redis 不会将 WRONGTYPE 作为事务中的错误返回

首先,让我展示如何重现我的问题:


在 docker 容器中运行 Redis

连接到 Redis 并执行以下命令:

> SET test 10

在 Go 中,运行以下代码:

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


这是预期的行为还是我错过了什么?


摇曳的蔷薇
浏览 248回答 1
1回答

饮歌长啸

Redis 事务中的每个命令都有两个结果。一种是将命令添加到事务中的结果,另一种是在事务中执行命令的结果。该Do方法返回将命令添加到事务的结果。Redis EXEC命令返回一个数组,其中每个元素都是在事务中执行命令的结果。检查每个元素以检查单个命令错误:values, err := redis.Values(redisClient.Do("EXEC"))if err != nil {&nbsp; &nbsp; // Handle error}if err, ok := values[0].(redis.Error); ok {&nbsp; &nbsp; // Handle error for command 0.&nbsp; &nbsp; // Adjust the index to match the actual index of&nbsp;&nbsp; &nbsp; // of the HMSET command in the transaction.}用于测试事务命令错误的辅助函数可能很有用:func execValues(reply interface{}, err error) ([]interface{}, error) {&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; values, ok := reply.([]interface{})&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; return nil, fmt.Errorf("unexpected type for EXEC reply, got type %T", reply)&nbsp; &nbsp; }&nbsp; &nbsp; for _, v := range values {&nbsp; &nbsp; &nbsp; &nbsp; if err, ok := v.(redis.Error); ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return values, err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return values, nil}像这样使用它:values, err := execValues(redisClient.Do("EXEC"))if err != nil {&nbsp; &nbsp; // Handle error.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go