9

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')
end
...

But if the json_str is badly formated, the decode() 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?

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
coanor
  • 3,746
  • 4
  • 50
  • 67

2 Answers2

9

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
    ...
else
    -- res contains the error message
    ...
end
abagshaw
  • 6,162
  • 4
  • 38
  • 76
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • @Egor Skriptunoff That depends on the interface of the `decode` call. I was just trying to illustrate the use of `pcall`. – ComicSansMS Jun 04 '13 at 13:08
  • IMO, the line `if res == nil then` in the question is pretty clear about this feature of `decode` call. – Egor Skriptunoff Jun 04 '13 at 13:23
  • @Egor Skriptunoff Yes, but that code assumed `decode` to return normally in the failure case (i.e. not via a longjmp triggered by `error`), which clearly it does not. – ComicSansMS Jun 04 '13 at 13:29
4

In your example, if you are using CJSON version 2.1.0, there is a new "cjson.safe" module, which will return nil and error msg if any exception occurred in encode or decode procedure.

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
rocky qi
  • 1,479
  • 1
  • 9
  • 6