Phoenix Ecto how to handle NoResultsError
Can catch the error using try, rescue
as well
def show(conn,%{"id" => id}) do
try do
result =
Repo.get!(MyModel, id)
{:ok, result}
rescue
Ecto.NoResultsError ->
{:error, :not_found, "No result found"}
end
end
Use get
instead of get!
and handle the logic when it returns nil
:
def show(conn,%{"id" => id}) do
case Repo.get(MyModel, id) do
nil -> # return null and 404
record -> # do something with record
end
end