Handle badarg in Erlang

2019-07-05 16:42发布

问题:

I am very new to the Erlang and I am getting badarg error when I try to convert binary to string as shown below.

Prefix = binary:bin_to_list(wh_json:get_ne_value(<<"prefix">>, Patterns)),

where Patterns are:

Pattern1--> {[{<<"prefix">>,<<>>},{<<"callerId">>,<<"1001">>},{<<"cid_regex">>,<<"^\\+?1001">>}]}

Pattern2--> {[{<<"prefix">>,<<"12">>},{<<"callerId">>,<<"1001">>},{<<"cid_regex">>,<<"^\\+?1001">>}]}

for Pattern2 it works fine but for Pattern1 I am getting this error because prefix does not have any value in Pattern1.

So, can any one tell me how I can handle this situation where prefix value can be null or any value, it should work for both the conditions.

回答1:

Check whether wh_json:get_ne_value returns undefined before calling binary:bin_to_list:

Prefix =
    case wh_json:get_ne_value(<<"prefix">>, Patterns) of
        undefined ->
            prefix_not_found;
        BinaryPrefix when is_binary(BinaryPrefix) ->
            binary:bin_to_list(BinaryPrefix)
    end