2017-09-01 29 views
0

我試圖發送JSON,當路徑不匹配。從error_view.ex,我的事情錯誤第一命中:Elixir/Phoenix渲染JSON ErrorView

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

config/config.exs更新render_error選項:

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

感謝您的幫助!這確實是重複的,我已經做了相應的標記。 – Ilya