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:

  1. We define a custom error type arg_error as a record, which is similar to a struct in other languages.

  2. The error_message/1 function is equivalent to the Error() method in Go. It formats the error message.

  3. The f/1 function demonstrates how to return a custom error. When the argument is 42, it returns an error tuple with our custom arg_error record.

  4. In the main/0 function, we use pattern matching to check if the result of f(42) matches our custom error type. This is similar to using errors.As in Go.

To run this program:

$ erlc custom_errors.erl
$ erl -noshell -s custom_errors main -s init stop
42
can't work with it

In 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.