How to get try / catch to work in Erlang?

I am pretty new to Erlang, and I am trying to get a basic try / catch statement to work.
I am 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.

Note that the JSON data is invalid.

to_text(ReqData, Context) ->    
    Body =  "{\"firstName\": \"John\"\"lastName\": \"Smith\"}",
    try decode(Body) of
  _ -> {"Success! Json decoded!",ReqData,Context}
  _ -> {"Error! Json is invalid",ReqData,Context}

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.

                            ": \"Smith\"}",

What exactly am I doing wrong?
The 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.


  • 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:

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

    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.