2015-12-06 13 views
6

Nella mia API Phoenix JSON ottengo un Ecto NoResultsError quando richiedo un oggetto che non esiste nel database.Phoenix Ecto come gestire NoResultsError

Desidero che la mia API JSON restituisca un valore null insieme a un errore 404.

Come faccio?

Attualmente ho praticamente hanno un default generato controllore html/vista ecc Ho modificato il controller in questo modo:

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 

insieme con la vista:

defmodule MyProject.MyModelView do 
    use Laired.Web, :view 

    def render("show.json", %{my_model: my_model}) do 
    my_model 
    end 
end 

correlati:

Setting up custom response for exception in Phoenix Application

risposta

10

Utilizzare invece get di get! e gestire la logica quando restituisce 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 
Problemi correlati