database type_error ai_generated true

redis.exceptions.ResponseError: 运行脚本时出错(调用 f_abcdef123456):@user_script:1: WRONGTYPE 操作针对持有错误类型值的键

redis.exceptions.ResponseError: Error running script (call to f_abcdef123456): @user_script:1: WRONGTYPE Operation against a key holding the wrong kind of value

ID: database/redis-lua-script-execution-error

其他格式: JSON · Markdown 中文 · English
88%修复率
90%置信度
1证据数
2023-09-05首次发现

版本兼容性

版本状态引入弃用备注
Redis 7.2.4 active
Redis 6.2.14 active
Redis Stack 7.2.0 active

根因分析

Redis Lua 脚本尝试对键执行与存储的数据类型不兼容的操作(例如对字符串键执行 LPUSH),导致 WRONGTYPE 错误。

English

A Redis Lua script attempted to perform an operation (e.g., LPUSH on a string key) that is incompatible with the data type stored at the key, causing a WRONGTYPE error.

generic

官方文档

https://redis.io/docs/latest/develop/interact/programmability/error-handling/

解决方案

  1. Identify the offending key by running: TYPE <key> in redis-cli. Then either delete the key (DEL <key>) or modify the script to handle the existing type (e.g., use EXISTS to check type before operations).
  2. Update the Lua script to use TYPE command to check the key's type before performing operations, and return an error or handle gracefully: local keyType = redis.call('TYPE', KEYS[1]); if keyType ~= 'list' then return redis.error_reply('Expected list, got ' .. keyType) end
  3. If the key should be a list but is currently a string, convert it by deleting and recreating: DEL mykey; LPUSH mykey value1 value2; then retry the script.

无效尝试

常见但无效的做法:

  1. Flushing all keys with FLUSHALL to clear the data type mismatch 95% 失败

    This deletes all data, which is an extreme measure; the script will still fail if the same key is recreated with the wrong type.

  2. Ignoring the error and retrying the script 100% 失败

    The error is deterministic; retrying without fixing the key type will produce the same error every time.

  3. Using EVAL instead of EVALSHA to force script recompilation 90% 失败

    The error is not due to script caching; it's a runtime type mismatch. EVAL will still fail with the same error.