当路线不匹配时,我正在尝试发送json。从error_view.ex
开始,我首先遇到错误:
def template_not_found(_template, assigns) do
render "404.html", assigns
end
但如果我将其更改为:
def template_not_found(_template, assigns) do
%{message: "custom error"}
end
它实际上并不发送json,而是返回no function clause matching in Phoenix.Template.HTML.encode_to_iodata!/1
。
我相信这是因为它希望发送一些HTML。是否可以将其更改为发送json?
我的路由器:
defmodule AppWeb.Router do
use AppWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", AppWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
scope "/api", AppWeb do
pipe_through :api
end
end
答案 0 :(得分:1)
在config/config.exs
更新render_error
选项:
config :my_app, MyApp.Endpoint,
render_errors: [view: MyApp.ErrorView,
format: "json",
accepts: ~w(json)]