Custom Errors in Erlang
-module(custom_errors).
-export([main/0]).
% A custom error type usually has a descriptive name.
-record(arg_error, {arg :: integer(), message :: string()}).
% Adding this function makes arg_error implement
% the error behaviour.
error_message(#arg_error{arg = Arg, message = Message}) ->
io_lib:format("~p - ~s", [Arg, Message]).
f(42) ->
% Return our custom error.
{error, #arg_error{arg = 42, message = "can't work with it"}};
f(Arg) ->
{ok, Arg + 3}.
main() ->
% In Erlang, pattern matching is used for error handling.
% This is similar to errors.As in Go.
case f(42) of
{error, #arg_error{arg = Arg, message = Message}} ->
io:format("~p~n", [Arg]),
io:format("~s~n", [Message]);
_ ->
io:format("err doesn't match arg_error~n")
end.In Erlang, we can implement custom error handling using records and pattern matching. Here’s a breakdown of the code:
We define a custom error type
arg_erroras a record, which is similar to a struct in other languages.The
error_message/1function is equivalent to theError()method in Go. It formats the error message.The
f/1function demonstrates how to return a custom error. When the argument is 42, it returns an error tuple with our customarg_errorrecord.In the
main/0function, we use pattern matching to check if the result off(42)matches our custom error type. This is similar to usingerrors.Asin Go.
To run this program:
$ erlc custom_errors.erl
$ erl -noshell -s custom_errors main -s init stop
42
can't work with itIn Erlang, we first compile the module with erlc, then run it using the erl command. The -noshell option runs Erlang without an interactive shell, -s custom_errors main calls the main/0 function in our module, and -s init stop ensures the Erlang runtime stops after our program finishes.
This example demonstrates how Erlang’s pattern matching and record system can be used to implement custom error types and error handling, providing functionality similar to Go’s custom errors and the errors.As function.