Phoenix Ecto how to handle NoResultsError

In my Phoenix JSON API, I get an Ecto NoResultsError when I query for an object that does not exist in the database.

I want my JSON API to return null with a 404 error.

How can I do it?

Currently, I pretty much have a default html controller / views created, etc. I modified the controller as follows:

def show(conn, %{"id" => id}) do my_model = Repo.get!(MyModel, id) case get_format(conn) do "json" -> render(conn, my_model: my_model) _ -> render(conn, "show.html", my_model: my_model) end end 

together with the presentation:

 defmodule MyProject.MyModelView do use Laired.Web, :view def render("show.json", %{my_model: my_model}) do my_model end end 

on this topic:

Configuring a custom response for exception in Phoenix app

+8
source share
2 answers

Use get instead of get! and process 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 
+13
source

Can catch a bug using try, rescue and also

 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 
0
source

All Articles