giusdp

giusdp

Refactor functions that can return different kind of errors

Hi all,

I was wondering on the best way to have a function that can return multiple errors. For example, I have something like this:

  @spec run_some_work(atom(), Params.t()) ::
          {:ok, Result.t()}
          | {:error, :bad_params}
          | {:error, :not_found}
          | {:error, :no_workers}
          | {:error, :worker_error}

The function can fail in different ways, and for each it has a different :error. in the @spec. I list them all so from the outside I can clearly see how to work with this function.

The problems that I’m having is that having functions with a big list of return types is cluttering my files, and that I have to update every spec if I add something new.

What’s your approach with functions that can give different errors? I was thinking about creating some sort of struct MyError, where the docs and specs would describe the possible errors it can contain, so in the function I would be just returning a single MyError struct.

Thanks in advance.

Marked As Solved

al2o3cr

al2o3cr

On a purely mechanical level, you can solve these problems with @type - anywhere you can write a basic type, you can instead write a custom one:

@type work_errors :: {:error, :bad_params} | {:error, :not_found} | {:error, :no_workers} | {:error, :worker_error}

@spec run_some_work(...) :: {:ok, Result.t()} | work_errors

That addresses both the “this takes up a lot of space” issue as well as “this is an updating headache” issue.

HOWEVER

A better question would be who’s handling those errors, and how. If they’re doing:

case run_some_work(...) do
  # etc
  {:error, _} ->
    yolo_try_it_again
end

then there’s not much value to maintaining detailed errors all the way up the stack. In that case, collapsing to a simpler error payload at a sensible boundary might make things clearer.

Finally, if the problem is likely to go away by just trying again (and if your data model tolerates it) you could consider “handling” errors like :no_workers by crashing.

Also Liked

dimitarvp

dimitarvp

I’m sure somebody will show up and tell me I’m wrong but I frankly don’t care about exceptions in Elixir. And the whole other throw, raise and rescue stuff. I ignore them on purpose.

I have only reached for them when it was made clear to me that a worker cannot ever crash (and thus be auto-restarted) at which point I just said “okay, fair” and bullet-proofed it.

In every single other case, so 99.9%, I’ll reach for everything else but not exceptions / throws / raises. If something is that brittle and can crash periodically – but recovers by itself little later – then I’ll just wrap it in a GenServer and communicate through messages with it (so as the caller doesn’t crash right away). But if that keeps crashing then it’s best for your app to go down because you have an unrecoverable error, in which case exceptions wouldn’t help at all anyway.


TL;DR: there’s a very good reasoning behind the “let it crash” philosophy, provided you have taken some precautions (which the OTP either gives you by default or makes extremely easy for you to set up e.g. amount of process restarts before giving up, timeouts etc).

cmo

cmo

You can use defexception to define the error, which you can pass around as a struct or raise.

You can also define the list of errors as a @type if you’re repeating them.

cmo

cmo

You’re wrong! :wink:

An exception is a struct, so you can be more specific about the cause and house more details/context than a simple atom. You don’t have to raise it.

For example, I have an external system that can return either a windows or app error code, which we turn into one of two exceptions with the code and message. I can easily distinguish between them and handle the different error cases.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

We're in Beta

About us Mission Statement