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.

Last Post!

giusdp

giusdp

Thanks everyone for the advice and the interesting discussion about the defexception, and the two schools of thoughts behind :smile:

In my case I don’t want to fall in the over-engineering trap so I’ll just use a @type to make the code less verbose and move on. If I find myself having to add more errors I will come back here and take a decision.

Probably I will do as @al2o3cr said and check out if I can move the error handling to a boundary, so I keep a lighter error type inside the core logic.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
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 31494 112
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42533 114
New

We're in Beta

About us Mission Statement