Elixir / Phoenix在ErrorView

时间:2017-09-01 06:09:33

标签: json elixir phoenix-framework

当路线不匹配时,我正在尝试发送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

1 个答案:

答案 0 :(得分:1)

config/config.exs更新render_error选项:

config :my_app, MyApp.Endpoint,
  render_errors: [view: MyApp.ErrorView,
                  format: "json",
                  accepts: ~w(json)]