How to make try / catch work in erlang

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.

+4
source share
1 answer

The log sentence "_ β†’ ..." allows only exceptions of the "throw" class. To catch other types of exceptions, you need to write a template in the form "Class: Term β†’ ..." (ie. The default class is "throw"). In your case:

 catch _:_ -> {"Error! Json is invalid",ReqData,Context} end 

When you do this, you should always ask yourself why you are catching all possible exceptions. If this is due to the fact that you are calling third-party code that does not know how it can behave, this is usually normal. If you call your own code, remember that you basically discard all the crash information, it might make debugging a lot harder. If you can narrow it down to catch only certain expected cases and allow any other exceptions (so you see where the real crash happened), then do it.

+14
source

All Articles