Ecto.StaleEntryError (or Ecto.NoResultsError) how to handle properly?

163 views
Skip to first unread message

Filip Moens

unread,
Sep 13, 2016, 6:28:04 AM9/13/16
to phoenix-talk


I'm trying to use optimistic locking in my application.

My code up until now (without optimistic locking) is reasonably clean.
Changesets, transactions, unique and foreign db constraints (through changesets), it all works well.

Now, when updating stale data (using optimistic_lock) an Ecto.StaleEntryError is thrown.
So far, I didn't have to catch errors, but I wonder how to properly handle Ecto.StaleEntryErrors being thrown in a GENERAL way.
By "in a GENERAL way" I mean I don't want to repeat this for every controller where it could happen.

How / where is this done best?

I could do some processing in the ErrorView module handling a server 500 error, but that doesn't seem to be the right (best) place.
And it feels late in the pipeline.

A try catch in the router is a possibility, but that doesn't feel right either.

(Basically my question applies also to Repo.get! or Repo.one! function calls failing with Ecto.NoResultsError)

Filip

Filip Moens

unread,
Sep 13, 2016, 8:19:58 AM9/13/16
to phoenix-talk
Should I do something like this:

defmodule MyApp.StaleEntryError do

defimpl Plug.Exception, for: Ecto.StaleEntryError do
def status(_exception), do: 404
end

end

and in the ErrorView:

def render("404.json", assigns) do
case assigns[:reason] do
%Ecto.StaleEntryError{} -> %{error: "optimistic.lock.stale.data"}
...
end
end

Reply all
Reply to author
Forward
0 new messages