3 ms·
Well, this isn't the only way to do things. There are exceptions in elixir and you can catch them if you want. But most functions that can fail have two version
by el_oni 3y ago
Well, this isn't the only way to do things. There are exceptions in elixir and you can catch them if you want. But most functions that can fail have two versions
File.read() returns {:OK, contents} or {:error, reason}
So you can pattern match on the result.
File.read!() returns contents or raises an exception.
The first one allows you to use errors as values and handle the problem at the source. The latter assumes its going to be successful and either makes you catch the exception or, more likely for elixir, let the process crash.
The with statement is a good fit for certain domains where otherwise you might have a bunch of nested cases.
If you are worried about it returning a different type you can wrap it in the else block
with {:ok, bar} <- func(foo)
do
bar
else
value -> {:failed, value}
end
So you can make your failed cases more homogeneous to pattern match on. You can even pattern match on the different failed cases if you want to ensure more homogeneity.
If using with doesn't make sense for the domain there are other constructs in the language that will