gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:36:35 28 4
gpt4 key购买 nike

我采用了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,并没有类似回调的错误处理。我想知道是否有任何 Lua 机制允许我从 file.lua 中处理 LuaJSON 中发生的错误?

最佳答案

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

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

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

关于json - 如何从 Lua 中的第三方库捕获错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com