[erlang-questions] When to return {ok, Value} or just the Value

Richard Carlsson carlsson.richard@REDACTED
Wed Nov 16 01:38:14 CET 2011


On 2011-11-15 22:56, David Mercer wrote:
> What criteria should I use in deciding whether an error should terminate the
> process (exit) or not (error)?  Either way, if not caught, it terminates the
> process, and, if caught, it doesn't.  If I'm writing a function and there is
> an error, why would I decide, "this error should terminate the process" and
> "this error should not"?  The function usually isn't even process-aware;
> it's a function that does something; or not, and then it errors.  It doesn't
> care whether it is part of a supervision tree or linked web of processes; it
> just wants to signal an error, and let the caller decide whether to catch it
> or crash.  Why is the erroring function giving a hint to the caller as to
> how to handle its errors, and, really, what does the hint even mean, since
> it seems to make no effective difference?

Effectively, no, any uncaught exception of any kind will terminate the 
process. But using exit(X) indicates that you know this code is running 
as part of a process which should at this point die unless someone for 
some even better reason decides to catch the exception, and the value X 
is something that some other process might be looking for in an 'EXIT' 
or 'DOWN' message. And of course, 'exit(normal)' has the special meaning 
of terminating the process just as if it had simply returned from its 
initial call - any linked processes which are not trapping exit signals 
will stay alive if they receive an exit signal with the reason 'normal', 
while any other exit reason will cause them to fail and propagate the 
same signal. In any case, a process terminating due to an explicit 
exit(X) is considered to be a controlled termination, and the Erlang 
error logger will not log this.

Using error(X), on the other hand, says that you just want to signal an 
error but with no particular intent of ending the process; it is not 
possible to proceed, but the caller might want to catch the exception 
and try something else. Your code has no opinion on what to do on a 
process level. An uncaught error (or throw) will terminate the process 
and also bring down any non-error-trapping linked processes, and the 
error logger will log the crash as an anomalous process termination.

    /Richard



More information about the erlang-questions mailing list