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