【问题标题】:How to capture error message from third-party-library in Lua?如何从 Lua 中的第三方库捕获错误消息?
【发布时间】:2013-06-04 08:00:11
【问题描述】:

我采用了LuaJSON 来解析 JSON。解析调用看起来像这样:

-- file.lua
local res = json.decode.decode(json_str)
if res == nil then
    throw('invalid JSON')
end
...

但如果json_str 格式错误,decode() 将在 LuaJSON 中停止并中断 file.lua 的执行。我希望控制流返回到我的函数,因此我可以提供自定义错误通知。

我浏览了 LuaJSON API,并没有 callback-like 错误处理。我想知道是否有任何 Lua 机制允许我从 file.lua 中处理 LuaJSON 中发生的错误?

【问题讨论】:

    标签: json lua ierrorhandler


    【解决方案1】:

    这里的问题是decode函数如果遇到错误会调用error

    这相当于 Lua 的异常处理机制。你要做的是调用protected mode中的decode函数:

    local success, res = pcall(json.decode.decode, json_str);
    if success then
        -- res contains a valid json object
        ...
    else
        -- res contains the error message
        ...
    end
    

    【讨论】:

    • @Egor Skriptunoff 这取决于decode 调用的接口。我只是想说明pcall 的用法。
    • IMO,问题中的if res == nil then 行非常清楚decode 呼叫的此功能。
    • @Egor Skriptunoff 是的,但该代码假定decode 在失败情况下正常返回(即不是通过error 触发的longjmp),显然它没有。
    【解决方案2】:

    在您的示例中,如果您使用的是 CJSON 版本 2.1.0,则有一个新的“cjson.safe”模块,如果在编码或解码过程中发生任何异常,它将返回 nil 和错误消息。

    local decoder = require("cjson.safe").decode
    local decoded_data, err = decoder(data)
    if err then
        ngx.log(ngx.ERR, "Invalid request payload:", data)
        ngx.exit(400)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2019-01-18
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多