2013-06-04 49 views
5

我已經採用了LuaJSON來解析JSON。解析調用好像是:如何從Lua中的第三方庫捕獲錯誤消息?

-- 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機制,允許我處理在LuaJSON中發生的錯誤,從file.lua

回答

9

這裏的問題是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 
+1

也許,'如果成功和res'然後會更正確? –

+0

@Egor Skriptunoff這取決於'decode'調用的接口。我只是試圖說明使用'pcall'。 – ComicSansMS

+0

國際海事組織,在這個問題上'如果res == nil then'這行'很清楚'decode'調用的這個特性。 –

0

在您的例子,如果你正在使用CJSON版本2.1.0,有一個新的「cjson.safe」模塊,該模塊將返回零和如果在編碼或解碼過程中發生任何異常,則爲錯誤消息。

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