Search code examples
elixirecto

How to gracefully show error in Ecto / Elixir?


Something like Repo.get!(User, 10)

Bring a result like:

(Ecto.NoResultsError) expected at least one result but got none in query:

from u in Db.User,
  where: u.id == ^10

    (ecto) lib/ecto/repo/queryable.ex:80: Ecto.Repo.Queryable.one!/4

How can I gracefully return something like {:error, "No Record found"}

I can use try do block however it is frowned upon in Elixir. Or I can use Recursive function method

I thought something like this (doesn't work though, just a concept):

def find_user(id) do
  case res = Repo.get!(User, id) do
     Ecto.NoResultsError -> {:error, "not found"}
     _ -> {:ok, res}
   end
end

This is not a Phoenix application.


Solution

  • Use Repo.get/2 and check for nil.

    case Repo.get(User, id) do
      nil -> {:error, :not_found}
      user -> {:ok, user}
    end