Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get try / catch to work in erlang

i'm pretty new to erlang and i'm trying to get a basic try / catch statement to work. I"m using webmachine to process some requests and all i really want to do is parse some JSON data and return it. In the event that the JSON data is invalid, I just want to return an error msg. Here is the code I have so far.

(the 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 the text, i get the following error back.

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? documentation says the "catch" statement handles all errors, or do i have to do something to catch a specific error that is thrown by mochijson:decode. Please any leads or advice would be helpful. Thanks.

like image 731
user436605 Avatar asked Dec 10 '10 19:12

user436605


1 Answers

The catch-clause _ -> ... only catches exceptions of the 'throw' class. To catch other kinds of exceptions, you need to write a pattern on the form Class:Term -> ... (i.e., 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're catching every possible exception. If it's because you're calling third-party code that you don't know how it might behave, it's usually OK. If you're calling your own code, remember that you're basically throwing away all information about the failure, possibly making debugging a lot more difficult. If you can narrow it down to catching only particular expected cases and let any other exceptions fall through (so you see where the real failure occurred), then do so.

like image 186
RichardC Avatar answered Sep 19 '22 06:09

RichardC