Reputation: 9995
What I am trying to do is mochijson2:decode(Ccode)
generates any exception or error, program execution should not stop and case branch {error, Reason} should get executed.
But when I am trying to get it implemented, it generates error at first line while checking and code doesn't continue execution for lines below it.
SCustomid = case mochijson2:decode(Ccode) of
{struct, JsonDataa} ->
{struct, JsonData} = mochijson2:decode(Ccode),
Mvalll = proplists:get_value(<<"customid">>, JsonData),
Pcustomid = erlang:binary_to_list(Mvalll),
"'" ++ Pcustomid ++ "'";
{error, Reason} -> escape_str(LServer, Msg#archive_message.customid)
end,
You could suggest if I need to use Try Catch. I am a bit experienced with Ejabberd but newbie for Erlang. Any help is appreciated.
Upvotes: 0
Views: 190
Reputation: 1818
You can use this:
SCustomid = try
{struct, JsonData} = mochijson2:decode(Ccode),
Mvalll = proplists:get_value(<<"customid">>, JsonData),
Pcustomid = erlang:binary_to_list(Mvalll),
"'" ++ Pcustomid ++ "'"
catch _:_ -> escape_str(LServer, Msg#archive_message.customid)
end
Upvotes: 1
Reputation: 2040
Seems the reason is an exception happens in mochijson2:decode/1. The function doesn't return a error as a tuple, instead the process crashes. There isn't enough information to tell what exactly the reason is. However I guess that the data format of Ccode
might be wrong. You can handle exception using try ... catch
statement:
SCustomid = try
case mochijson2:decode(Ccode) of
{struct, JsonDataa} ->
{struct, JsonData} = mochijson2:decode(Ccode),
Mvalll = proplists:get_value(<<"customid">>, JsonData),
Pcustomid = erlang:binary_to_list(Mvalll),
"'" ++ Pcustomid ++ "'";
{error, Reason} ->
escape_str(LServer, Msg#archive_message.customid)
end
catch
What:Reason ->
escape_str(LServer, Msg#archive_message.customid)
end,
Or just catch
:
SCustomid = case catch(mochijson2:decode(Ccode)) of
{struct, JsonDataa} ->
{struct, JsonData} = mochijson2:decode(Ccode),
Mvalll = proplists:get_value(<<"customid">>, JsonData),
Pcustomid = erlang:binary_to_list(Mvalll),
"'" ++ Pcustomid ++ "'";
{error, Reason} ->
escape_str(LServer, Msg#archive_message.customid);
{What, Reason} ->
escape_str(LServer, Msg#archive_message.customid)
end,
Upvotes: 1