У меня есть следующий контроллер:Phoenix плагин для проверки необходимых паров запроса
defmodule Campaigns.CampaignController do
use Campaigns.Web, :controller
alias Campaigns.Campaign
alias Campaigns.ApiParams
plug :ensure_account_id
def index(conn, %{"account_id" => account_id}) do
query = from c in Campaign, where: [account_id: ^account_id]
render(conn, "index.json", campaigns: Repo.all(query))
end
def show(conn, %{"id" => id, "account_id" => account_id}) do
query = from c in Campaign, where: [id: ^id, account_id: ^account_id]
render(conn, "show.json", campaign: Repo.one(query))
end
defp ensure_account_id(conn, _) do
cs = ApiParams.changeset(%ApiParams{}, conn.params)
case cs do
%{:params => %{"account_id" => account_id}, :valid? => true} ->
conn
_ ->
conn
|> put_status(400)
|> render(conn, "400.json", "account_id is missing")
end
end
end
Я желающий убедиться, что account_id
присутствует в просьбе, для каждой конечной точки в этом контроллере. Ошибка в консоли я получаю это
[error] #PID<0.403.0> running Campaigns.Endpoint terminated
Server: localhost:4000 (http)
Request: GET /api/campaigns/1
** (exit) an exception was raised:
** (FunctionClauseError) no function clause matching in Phoenix.Controller.render/4
Но у меня есть метод render("400.json"
в моем файле ErrorView.ex.
Вот мой ErrorView.ex
файл
defmodule Campaigns.ErrorView do
use Campaigns.Web, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
def render("400.json", %{"message" => error}) do
%{error: error}
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
'put_status/2' вернуться' conn'so вы должны удалить 'conn' в вашем' render' функции – TheAnh
К сожалению, Я новичок в Phoenix/Elixir, что вы имеете в виду? – dennismonsewicz