Error handling patterns

The exceptions lesson shows the three classes and the shape of try. This lesson is about where each one belongs in a program: the {ok, Value} | {error, Reason} tuple for a failure the caller must read, a throw that aborts a deep parse and is caught at its entrance, and a boundary process that catches a crash so the rest of the system keeps its shape. Every Erlang program uses one of these three, and most use all of them.

The ok tuple

The normal path of a function that may fail returns a tuple: {ok, Value} when it worked and {error, Reason} when it did not. The caller matches on it, so the failure cannot be forgotten. When several steps follow each other, a small bind/2 keeps the happy path flat: it runs the next function only for an {ok, Value} and passes an error through untouched:

chain.erl

-module(chain). -export([main/0]). lookup(Key, Map) -> case maps:find(Key, Map) of {ok, Value} -> {ok, Value}; error -> {error, {missing, Key}} end. bind({ok, Value}, Fun) -> Fun(Value); bind({error, _} = Error, _Fun) -> Error. main() -> Data = #{host => "db.local", port => 5432}, Result = bind( lookup(host, Data), fun(Host) -> bind( lookup(port, Data), fun(Port) -> {ok, {Host, Port}} end ) end ), io:format("~p~n", [Result]), io:format("~p~n", [bind(lookup(user, Data), fun(User) -> {ok, User} end)]).

erlc chain.erl

erl -noshell -eval 'chain:main(), halt().'

{ok,{"db.local",5432}} {error,{missing,user}}

The second result shows the property that makes the shape useful: the first missing key stops the chain and its reason arrives unchanged. No step needs a case of its own, and no error is thrown away. A large program builds the same idea with more steps, and the caller still has one tuple to match.

A throw that aborts

Some checks sit deep inside a parse, where returning an error tuple at every level would add a branch to every helper. There a throw is the right tool: it carries the offending field to the one try at the entrance, which turns it into the ordinary error value. The public function still answers {ok, Value} | {error, Field}; the throw never escapes it:

form.erl

-module(form). -export([main/0, parse/1]). parse(Params) -> try Name = require(name, Params), Age = require(age, Params), check_age(Age), {ok, {Name, Age}} catch throw:{invalid, Field} -> {error, Field} end. require(Key, Params) -> case maps:find(Key, Params) of {ok, Value} -> Value; error -> throw({invalid, Key}) end. check_age(Age) when is_integer(Age), Age >= 0 -> ok; check_age(_Age) -> throw({invalid, age}). main() -> io:format("~p~n", [parse(#{name => <<"Ada">>, age => 36})]), io:format("~p~n", [parse(#{name => <<"Ada">>, age => -1})]), io:format("~p~n", [parse(#{age => 36})]).

erlc form.erl

erl -noshell -eval 'form:main(), halt().'

{ok,{<<"Ada">>,36}} {error,age} {error,name}

The catch clause names the class and the tag, so an unrelated throw or an error from a bug still escapes instead of being reported as a bad field. That precision is the difference between this pattern and a catch-all: the caller can trust that {error, Field} means a validation problem and nothing else. The shell shows the same function as a caller sees it:

erl

1> form:parse(#{age => 36}). {error,name} 2> form:parse(#{name => <<"Ada">>, age => 36}). {ok,{<<"Ada">>,36}}

The boundary that catches

A crash that no inner function can repair is caught once, at the boundary of the work: the function that turns a request into a reply. It keeps the reason and the fact that a stacktrace exists, and returns the error shape its caller already handles. The inner function simply calls error/1:

layer.erl

-module(layer). -export([main/0, request/1]). request(Input) -> try handle(Input) of Reply -> {ok, Reply} catch error:Reason:Stacktrace -> {error, {Reason, Stacktrace =/= []}} end. handle(<<"ping">>) -> pong; handle(<<"divide">>) -> error(division_by_zero); handle(Other) -> error({bad_request, Other}). main() -> io:format("~p~n", [request(<<"ping">>)]), io:format("~p~n", [request(<<"divide">>)]), io:format("~p~n", [request(<<"other">>)]).

erlc layer.erl

erl -noshell -eval 'layer:main(), halt().'

{ok,pong} {error,{division_by_zero,true}} {error,{{bad_request,<<"other">>},true}}

The boundary is also the place to log. In a real server the clause writes the reason and the stacktrace to logger before it answers, so the operator sees the crash while the client sees a stable error. The observability part of the course shows the log call, and the let it crash lesson explains why the boundary is a supervisor in a concurrent system.

The blind catch

The mistake that undoes all of the above is a catch-all at the boundary. This service answers every failure with the same atom, so the caller cannot tell a bad request from a broken program:

blind.erl

-module(blind). -export([main/0]). run(Input) -> try handle(Input) catch _:_ -> {error, unknown} end. handle(<<"ping">>) -> pong; handle(Other) -> error({bad_request, Other}). main() -> io:format("~p~n", [run(<<"ping">>)]), io:format("~p~n", [run(<<"stop">>)]).

erlc blind.erl

erl -noshell -eval 'blind:main(), halt().'

pong {error,unknown}

The second call sent a bad request, and the reply says nothing about it. A month later a genuinely broken clause fails the same way, and the log has no reason either. The fix is the clause of layer.erl: bind the class, the reason and the stacktrace, then decide what to keep.

Which layer handles what

The three shapes divide the work cleanly. A function that can fail for a reason the caller must handle returns an {ok, _} | {error, _} tuple, and the caller matches it. A deep parse that would otherwise thread an error through every helper throws its own tagged term and catches it at the entrance. A crash that no local code can repair is allowed to happen, and one boundary catches it, logs it and answers in the error shape of the protocol.

Two rules keep the layers honest. Do not catch what you cannot repair; the reason and the stacktrace are the only record of the bug, and a catch-all deletes both. And do not let a throw travel past the public function that started it; a caller that does not know the tag cannot catch it, so the tag leaks into the protocol.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a function return for a failure the caller must read?

    Answer

    {error, Reason}

    The error tuple carries the reason and forces the caller to match it.

  2. What does the bind/2 helper do with an {error, _} value?

    Answer

    Passes the error through untouched

    bind runs the next step only for {ok, Value}; an error is the result of the chain.

  3. Why is a throw useful inside a deep parse?

    Answer

    It aborts the parse to one catch at the entrance

    The throw carries the failing field to the one try, which turns it into the public error tuple.

  4. Why should the catch at the boundary name the class and the tag?

    Answer

    So an unrelated crash still escapes and is reported

    A precise clause keeps a bug from being reported as a validation error, and keeps its reason.

  5. What does this module print? -module(q1). -export([main/0]). lookup(Key, Map) -> case maps:find(Key, Map) of {ok, Value} -> {ok, Value}; error -> {error, missing} end. main() -> Map = #{port => 5432}, io:format("~p~n", [lookup(port, Map)]), io:format("~p~n", [lookup(host, Map)]).

    Answer

    {ok,5432} / {error,missing}

    The first key is present and its value is wrapped; the second is absent, so the error clause runs.

  6. What does this module print? -module(q2). -export([main/0]). parse(Params) -> try Age = require(age, Params), {ok, Age} catch throw:{invalid, Field} -> {error, Field} end. require(Key, Params) -> case maps:find(Key, Params) of {ok, Value} -> Value; error -> throw({invalid, Key}) end. main() -> io:format("~p~n", [parse(#{name => "Ada"})]).

    Answer

    {error,age}

    The missing age key throws {invalid, age}, and the catch clause turns it into {error, age}.

  7. What does this module print? -module(q3). -export([main/0]). run(Input) -> try handle(Input) catch error:Reason -> {error, Reason} end. handle(<<"stop">>) -> error(shutdown); handle(_Other) -> ok. main() -> io:format("~p~n", [run(<<"stop">>)]), io:format("~p~n", [run(<<"go">>)]).

    Answer

    {error,shutdown} / ok

    The first input raises shutdown, which the catch turns into an error tuple; the second returns ok.

  8. What does this module print? -module(q4). -export([main/0]). run(Input) -> try handle(Input) catch _:_ -> {error, unknown} end. handle(<<"ping">>) -> pong; handle(_Other) -> error(bad_request). main() -> io:format("~p~n", [run(<<"stop">>)]).

    Answer

    {error,unknown}

    The catch-all throws the reason away, which is exactly the mistake this lesson names.

  9. What happens to the stacktrace in a catch-all clause _:_ -> ok?

    Answer

    It is discarded

    The clause binds neither the class nor the stacktrace, so the only record of the bug is gone.

  10. Where should a throw be caught?

    Answer

    At the public function that started the operation

    The entrance that knows the tag turns the throw into the public error tuple; it must not leak further.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev