2017-09-01 3 views
0

J'essaye d'envoyer json, quand les routes ne correspondent pas. De error_view.ex, je chose les premiers hits d'erreur:Elixir/Phoenix rend json sur ErrorView

def template_not_found(_template, assigns) do 
    render "404.html", assigns 
end 

mais si je change à:

def template_not_found(_template, assigns) do 
    %{message: "custom error"} 
end 

Il n'envoie pas réellement JSON, au lieu me retourne no function clause matching in Phoenix.Template.HTML.encode_to_iodata!/1. Je crois que c'est parce qu'il s'attend à envoyer du code HTML. Est-il possible de le changer pour envoyer json?

Mon routeur:

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 

Répondre

1

Dans config/config.exs mise à jour l'option render_error:

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

Merci de l'aide! C'était en effet un doublon, j'ai marqué en conséquence. – Ilya