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

Fred Hebert mononcqc@REDACTED
Wed Nov 23 16:16:00 CET 2011

That's what throws are for.

init(Args) ->
    try check_opts(Args, [name, age, email]) of
       ok -> {ok, #state{opts=Args}}
       throw:Reason={missing_opt, _} -> {stop, Reason}

check_opts(Options, ToCheck) ->
    F = fun(Opt, OptList) ->
             case proplists:get_value(Opt, OptList) of
                undefined -> throw({missing_opt, Opt});
                _ -> OptList
    lists:foldl(F,Options, ToCheck),

This uses a tiny trick with folds to check for all options in a list and
make sure they're part of the list passed in. If any of them is missing, a
throw is called, returned in a list and init fails.

On Wed, Nov 23, 2011 at 9:50 AM, Joel Reymont <joelr1@REDACTED> wrote:

> I'm passing a proplist to the init function of my gen_server.
> I need to ensure various options are present and validate them.
> I also don't want to have a huge nested case statement.
> Is it acceptable to throw or error when I cannot find or validate an
> option?
> Are there better ideas?
> N.B. The option values are assigned to fields of the gen_server state
> records.
> --------------------------------------------------------------------------
> - for hire: mac osx device driver ninja, kernel extensions and usb drivers
> ---------------------+------------+---------------------------------------
> http://wagerlabs.com | @wagerlabs | http://www.linkedin.com/in/joelreymont
> ---------------------+------------+---------------------------------------
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20111123/957729ea/attachment.htm>

More information about the erlang-questions mailing list