Structs

Ulf Wiger etxuwig@REDACTED
Thu Jan 16 13:38:48 CET 2003


On Thu, 16 Jan 2003, Luke Gorrie wrote:

>I still have problems in Erlang in the cases where I don't
>want to crash, i.e. the non-assertion type of error
>detection. Here's a function I wrote recently:

If the philosophy of making functions return a correct value
or exit were followed more consistently, one only needs to
catch exceptions at the top and format a nice message.

The following implementation avoids the indentation misery.
We have to wrap some functions to give them correct-or-exit
semantics.

/Uffe

connect(Host, User, Password) ->
    case catch
	begin
	    Pid = open(Host),
	    user(Pid, User, Password),
	    Home = pwd(Pid),
	    type(Pid, binary),
	    {ok, Pid, Home}
	end of
	{'EXIT', Reason} -> {error,
otp_ftp:formaterror(Reason)};
	Result ->
	    Result
    end.

open(Host) ->
    ok_value(otp_ftp:open(Host)).
user(Pid, User, Password) ->
    ok(otp_ftp:user(Pid, User, Password)).
pwd(Pid) ->
    ok_value(otp_ftp:pwd(Pid)).
type(Pid, Type) ->
    ok(otp_ftp:type(Pid, Type)).

ok_value({ok, Result}) ->	Result;
ok_value({error, Reason}) ->	exit(Reason).

ok(ok) ->		ok;
ok({error, Reason}) ->	exit(Reason).



>  connect(Host, User, Password) ->
>      case otp_ftp:open(Host) of
>          {ok, Pid} ->
>              link(Pid),
>              case otp_ftp:user(Pid, User, Password) of
>                  ok ->
>                      case otp_ftp:pwd(Pid) of
>                          {ok, Home} ->
>                              ?event(ftp, "~p: Home is ~p", [self(), Home]),
>                              case otp_ftp:type(Pid, binary) of
>                                  ok ->
>                                      %% It is at about this level of nesting
>                                      %% that better exception handling in
>                                      %% erlang becomes appetizing..
>                                      {ok, Pid, Home};
>                                  {error, Rsn} ->
>                                      {error, otp_ftp:formaterror(Rsn)}
>                              end;
>                          {error, Rsn} ->
>                              {error, otp_ftp:formaterror(Rsn)}
>                      end;
>                  {error, Rsn} ->
>                      {error, otp_ftp:formaterror(Rsn)}
>              end;
>          {error, Rsn} ->
>              {error, otp_ftp:formaterror(Rsn)}
>      end.
>
>Cheers,
>Luke
>
>

-- 
Ulf Wiger, Senior Specialist,
   / / /   Architecture & Design of Carrier-Class Software
  / / /    Strategic Product & System Management
 / / /     Ericsson Telecom AB, ATM Multiservice Networks




More information about the erlang-questions mailing list