I am new to erlang and I am trying to get the basic try / catch statement to work. I use webmachine to handle some requests, and all I really want to do is parse some JSON data and return it. In case the JSON data is invalid, I just want to return an error message. still.
(JSON data is invalid)
to_text(ReqData, Context) -> Body = "{\"firstName\": \"John\"\"lastName\": \"Smith\"}", try decode(Body) of _ -> {"Success! Json decoded!",ReqData,Context} catch _ -> {"Error! Json is invalid",ReqData,Context} end. decode(Body) -> {struct, MJ} = mochijson:decode(Body).
The code compiles, but when I run it and send a request for text, I get the following error.
error,{error,{case_clause,{{const,"lastName"}, ": \"Smith\"}", {decoder,utf8,null,1,31,comma}}}, [{mochijson,decode_object,3}, {mochijson,json_decode,2}, {webmachine_demo_resource,test,1}, {webmachine_demo_resource,to_text,2}, {webmachine_demo_resource,to_html,2}, {webmachine_resource,resource_call,3}, {webmachine_resource,do,3}, {webmachine_decision_core,resource_call,1}]}}
What exactly am I doing wrong? the documentation says that the catch statement has all the errors, or I need to do something to catch a specific error that is caused by mochijson: decode. Please any recommendations or advice will be helpful. Thanks.