如何在Lua中从第三方库中捕获错误消息?

我采用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 APIs,但没有_callback-like_错误处理。我想知道是否有任何Lua机制可以允许我从_within_file.lua_中处理在LuaJSON中发生的错误?

点赞
用户577603
用户577603

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

这是Lua的异常处理机制的等效方式。你需要在保护模式下调用decode函数:

local success, res = pcall(json.decode.decode, json_str);
if success then
    -- res 包含有效的 json 对象
    ...
else
    -- res 包含错误消息
    ...
end
2013-06-04 08:53:51
用户4335683
用户4335683

在你的示例中,如果你正在使用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
2017-09-26 10:08:37