dogweather

dogweather

Ecto error handling: let exceptions bubble up?

In Ecto programming, could this be described as an anti-pattern?

# Database operation
Repo.some_operation(...)
rescue
  error ->
    Logger.error("Failed to do X: #{inspect(error)}")
    {:error, "Generic message"}  # ← System failure as business error

It seems like the answer is yes. I’m in the process of ripping out a bunch of this in a codebase.

FYI, the Dialyzer unmatched_return was the hint that I had a problem with my error handling. I’m a believer now.

EDIT: Here's ChatGPT o3-pro's answer to the question

Short answer – yes, it is an anti‑pattern.

Catching every exception that can bubble out of Repo.* and then returning a domain‑style {:error, …} tuple does more harm than good in most Elixir/Ecto codebases. Below is a breakdown of why it’s problematic and what to do instead.


1. What Ecto and Elixir’s “happy path” expect

Condition Normal, non‑bang call ( Repo.insert/2**,** Repo.update/2**, …)** Bang call ( Repo.insert!/2**, …)**
Validation / constraint failure (expected business error) {:error, %Ecto.Changeset{…}} Raises Ecto.InvalidChangesetError
DB connectivity, malformed SQL, serialization failure, etc. (system error) raises (DBConnection.ConnectionError, Postgrex.Error, …) raises (same)

Take‑away:

  • Business failures are already represented by return tuples.
  • System failures are already raised.You almost never need a rescue to tell them apart.

2. Why wrapping raised system errors in a generic

{:error, _}

is harmful

  1. Loses signal The caller can no longer discriminate between user‑facing problems (e.g., “email already taken”) and infrastructure problems (e.g., “couldn’t reach the database”). They both look like {:error, “Generic message”}.
  2. Breaks fault tolerance Elixir’s supervision philosophy is “let it crash.” A system error usually should crash the process so the supervisor can restart it (and you get a crash report with stack‑trace). Converting it into an ordinary return value prevents that safety net.
  3. Hides stack‑trace & root cause You log inspect(error), but unless you also log STACKTRACE, you’ve lost the most useful bit. Even then, the caller still has no context.
  4. Encourages defensive coding everywhere else Downstream functions must now handle phantom {:error, “Generic message”} tuples that were never in the Ecto contract, leading to boilerplate and accidental swallowing of real domain errors.

3. Better patterns

3.1 Use non‑bang APIs and pattern match

case Repo.insert(changeset) do
  {:ok, struct} ->
    {:ok, struct}

  {:error, %Ecto.Changeset{} = cs} ->
    {:error, cs}           # business error – propagate the changeset
end

If Repo.insert/2 raises (network down, bad migration, etc.) let it crash. Your supervisor, the Logger backend (or Sentry/AppSignal/etc.), and any retry strategy will handle the rest.

3.2 Use bang APIs

inside

supervised tasks

If you conceptually want “success or crash,” call the bang version in a short‑lived process you own (Task, GenServer handle‑call, etc.):

def create_user!(params) do
  changeset = User.changeset(%User{}, params)
  Repo.insert!(changeset)   # raises on infra failure OR bad changeset
end

The caller can choose whether to wrap that in try/rescue or link/monitor the task.

3.3 Translate only

expected

DB error codes

Occasionally you truly need to map a low‑level PG error to a domain error (e.g., unique‑violation for an idempotency key). Catch just that error and translate, preserving everything else:

try do
  Repo.insert!(row)
rescue
  e in Postgrex.Error ->
    if e.postgres.code == :unique_violation do
      {:error, :duplicate_key}
    else
      reraise e, __STACKTRACE__
    end
end

4. What to do with logging

  • Let your crash reporter or Logger backend capture uncaught errors globally.
  • Log business errors where they are handled (often in Phoenix controllers, Absinthe resolvers, or the calling service layer), not inside a blanket rescue.

5. When might rescuing be appropriate?

  1. External API timeout that you must degrade gracefully (still distinct from business logic).
  2. Known, isolated DB errors where retry or fallback is viable (e.g., transient serialization failures in a saga pattern).
  3. Migration scripts / mix tasks where you want the script to continue processing subsequent items.

Even there, rescue only the specific exception types you care about and keep the original Exception.message/1 so the operator can see what went wrong.


Bottom line

Rescuing all Repo. exceptions and returning {:error, _} conflates system failures with domain logic, obscures diagnostics, and undercuts OTP supervision.*

Prefer the natural Ecto contracts—pattern‑match on {:error, changeset} for business cases and let unexpected failures crash (or handle them narrowly).

Adopting this discipline keeps your codebase idiomatic, debuggable, and resilient.

Most Liked

camatcode

camatcode

Let it crash.

The only time I can think of when I catch ecto errors like that is when I want an invalid UUID to be the same as a UUID that doesnt exist

  @impl true
  def one(query, opts \\ []) do
    super(query, opts)
  rescue
    err in Ecto.Query.CastError ->
      if err.type == Ecto.UUID or match?({:in, Ecto.UUID}, err.type) do
        Logger.warning("Received invalid UUID #{err.value} in query #{inspect(query)}")
        nil
      else
        reraise err, __STACKTRACE__
      end
  end
tfwright

tfwright

The question you’re directly asking here has been thoroughly answered, and in fact it’s explicitly covered in Elixir docs, so you might want to give that whole section a read: Design-related anti-patterns — Elixir v1.18.4 (although personally I find that some of those issues are more stylistic decisions that come with tradeoffs than “genuine” anti-patterns).

But to go a bit further, since it sounds like you are new to the library… if you are getting exceptions from Ecto something may have already gone wrong. As you can see from the docs, most Ecto operations do not raise errors by default, instead they return error tuples already so there is no exception to let bubble up or not, and you have to use a separate ! version of the function to get it to raise, so you may want to check you are using the right API for your case. The operations that do raise errors “unexpectedly” mostly do so because the inputs are invalid (for example if you pass in value with a data type that doesn’t match the db field). In those cases you are missing some sort of validation higher up the call chain. If you want to provide more context about where you are running into this issue, we might be able to offer more specific advice.

krisleech

krisleech

I never knew about super

garrison

garrison

If you need to do actual error handling (e.g. a web form) then pretty much all Ecto errors (coming from the DB) can be converted to Changeset errors.

Otherwise, yeah, just let it crash. You can catch the error and handle it like you have, but it’s probably best to do that as high up as possible. For example, Phoenix would display an error 500 page to the client for such a request, but that is done arbitrarily for every error so that it can cover as many “unknown unknown” bugs as possible. You probably don’t want to be using try blocks like this in every code path, only at the top. And even in that case you might want to use a process to isolate the work instead. It depends on what you’re doing.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
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

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement