Reputation: 966
I am using the eredis erlang client and I am new to Erlang. I was wondering what might be wrong with the following function:
foo(Host, Port) ->
case catch eredis:start_link(Host, Port) of
{connection_error, {connection_error, _}} -> {error, "failed"};
{ok, Connection} -> {"done"};
_ -> {error, "Unknown"}
end.
My understanding is that given the above function and a valid Redis host:port e.g. localhost:6379 then if I do:
mymodule:foo('localhost', 6379).
I should get the answer
{"done"}
while if for example I do:
mymodule:foo('loc', 6379).
I should get:
{error, "failed"}
But in the latter case what I get is:
** exception exit: {connection_error,{connection_error,nxdomain}}
Could somebody kindly explain what am I doing wrong here?
Thanks
Upvotes: 1
Views: 484
Reputation: 18869
The problem is probably that your exception is stemming from the eredis_client
gen_server you start up with your start link. It is supposed to return {error, Term}
back to you and never throw an exception there. You are also linked to the process, so you may die due to this.
It is very rare that you need to do exception handling in Erlang. Here you can just handle errors directly
case eredis:start_link(Host, Port) of
{ok, Pid} -> {ok, Pid};
{error, Reason} -> {error, Reason}
end.
should be enough. In fact, you can just do
{ok, Pid} = eredis:start_link(Host, Port)
and utilize a crash if something goes wrong for the time being. The error you see due to nxdomain
is because you don't have the name 'loc'
.
Upvotes: 2