coanor coanor - 5 months ago 43
JSON Question

How to capture error message from third-party-library in Lua?

I have adopted the LuaJSON to parse JSON. The parse call seems like that:

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

But if the
is badly formated, the
will stop within LuaJSON and interrupt the execution of file.lua. I want the control flow to return to my function instead, so I can provide a custom error notification.

I have browsed the LuaJSON APIs, and there is no callback-like error handling. I want to know is there any Lua mechanism that allows me to handle errors occuring within LuaJSON from within file.lua?

Answer Source

The problem here is that the decode function calls error if it encounters an error.

This is Lua's equivalent to an exception handling mechanism. What you want to do is call the decode function in protected mode:

local success, res = pcall(json.decode.decode, json_str);
if success then
    -- res contains a valid json object
    -- res contains the error message
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download