[erlang-questions] try catch scope
Jesper Louis Andersen
jesper.louis.andersen@REDACTED
Tue Jun 29 23:53:04 CEST 2010
On Tue, Jun 29, 2010 at 11:21 PM, Wes James <comptekki@REDACTED> wrote:
> What is the scope of try/catch.
> has_query(A) ->
> try
> case length(yaws_api:parse_query(A)) of
[...]
> because if a user puts in an invalid character in the URL it crashes
> parse_query and I want the app to continue without erroring out in the
> browser.
>
> Is this because of the level of the error?
Yes (is my guess), see
http://www.erlang.org/doc/reference_manual/expressions.html#id2276021
on the try..catch construction. Since you omit the class, it is
defaulted to 'throw'. I would personally regard that as an error in
the interface of parse_query. My solution would be something akin to
safe_parse_query(A) ->
try
Q = yaws_api:parse_query(A),
{ok, Q}
catch
error:_ -> no_parse % You should really narrow down the class and
the error Reason to the right type here. I may be wrong.
end.
which transforms the function into a variant which is safer:
has_query(A) ->
case yaws_api:parse_query(A) of
no_parse -> false;
{ok, Q} when length(Q) == 0 -> false;
{ok, Q} -> true
end.
alternatively, no_parse can be an empty list, if you so want.
(Caveat: I only wrote the code and did not test it).
--
J.
More information about the erlang-questions
mailing list