[erlang-questions] throwing from gen_server:init/1

Joel Reymont joelr1@REDACTED
Wed Nov 23 16:05:30 CET 2011


On Nov 23, 2011, at 2:55 PM, Dmitry Demeshchuk wrote:

> Can be a single try-catch instead. As far as I remember, sasl won't
> show you proper error message if an exception occurs in init/1.


Something like this then?

1> Opts1 = [{'foo', 1}, {'bar', 2}].
[{foo,1},{bar,2}]

3> Opts2 = [{'foo', self()}, {'bar', 2}].
[{foo,<0.34.0>},{bar,2}]

4> Opts3 = [{'foo', self()}, {'bar', 'baz'}].
[{foo,<0.34.0>},{bar,baz}]

5> x:check(Opts1).
{error,{invalid_option,foo}}

6> x:check(Opts2).
{error,{invalid_option,bar}}

7> x:check(Opts3).
{ok,{state,<0.34.0>,baz}}

--- x.erl

-module(x).

-compile([export_all]).

-record(state, {
          foo :: pid(),
          bar :: atom()
         }).

-spec check(proplists:proplist()) -> {'ok', #state{}} | {'error', _}.

check(Opts) ->
  try
      Foo = ensure('foo', Opts, fun is_pid/1),
      Bar = ensure('bar', Opts, fun is_atom/1),
      {'ok', #state{ foo = Foo, bar = Bar }}
  catch
      error:X ->
          {'error', X}
  end.

ensure(Key, Opts, Guard) 
  when is_atom(Key),
       is_list(Opts),
       is_function(Guard) ->
    case proplists:get_value(Key, Opts) of
        'undefined' -> 
            error({'missing_option', Key});
        Value -> 
            case Guard(Value) of
                'true' -> Value;
                _      -> error({'invalid_option', Key})
            end
    end.


--------------------------------------------------------------------------
- for hire: mac osx device driver ninja, kernel extensions and usb drivers
---------------------+------------+---------------------------------------
http://wagerlabs.com | @wagerlabs | http://www.linkedin.com/in/joelreymont
---------------------+------------+---------------------------------------




More information about the erlang-questions mailing list