json.decode() error handling?

I'm making a web request that returns JSON and I'm passing it to json.decode(). How do I handle instances where I get an http error response (like a 503, etc which is HTML)?

Currently it just spits out:
: Lua Runtime Error: lua_pcall failed with status: 2, error message is: Invalid input: '

The documentation doesn't specify any sort of return value for error conditions like invalid input.

I just test the response with string match html... but offcourse then you have to be sure html will not appear in your json file.

1
2
3
4
5
6
7
8
9
10
11
12
13
local function networkListener( event )                 
                        if ( event.isError ) then
                                print ("error")
                        else
                                local response = event.response
                                if ( string.match (response, "html" )) then
                                        print ( "error")
                                else
                                        local content = json.decode( response )
                                        
                                end
                        end
                end

1
2
3
4
5
6
7
8
9
10
-- catch json errors
local succ, data = pcall(function()
        return json.decode(event.response)
end)
                        
if succ then
        doStuffWith(data)
else
        print("Error parsing JSON")
end

Thanks to both for your responses! ojnab, good workaround but as you mention it would be an issue if the JSON contains the same string. hoan, thank you for the general solution. I think this is probably how it was intended to be used and thanks for the code snippet as I'm still learning Lua. Here's the reference for those who might want to look up more info on Lua exception handling:

http://www.lua.org/pil/8.4.html

views:2194 update:2011/9/26 8:07:09
corona forums © 2003-2011