10

phoenix で安らかな API (json) をビルドします。そして、html のサポートは必要ありませんでした。

フェニックスのエラーをオーバーライドするには? エラー例: - 500 - ルートが見つからない場合の 404 など。

4

4 に答える 4

8

For those who may have the same issues I had, there a couple of steps required to render JSON for 404 and 500 responses.

Firstly add render("404.json", _assigns) and render("500.json", _assigns) to your app's web/views/error_view.ex file.

For example:

defmodule MyApp.ErrorView do
  use MyApp.Web, :view

  def render("404.json", _assigns) do
    %{errors: %{message: "Not Found"}}
  end

  def render("500.json", _assigns) do
    %{errors: %{message: "Server Error"}}
  end
end

Then in your config/config.exs file updated the default_format to "json".

config :my_app, MyApp.Endpoint,
  render_errors: [default_format: "json"]

Note that if your app is purely a REST api this will be fine, but be careful in the event you also render HTML responses as now by default errors will be rendered as json.

于 2015-07-29T00:45:46.967 に答える
4

をカスタマイズする必要がありますMyApp.ErrorView。Phoenix はこのファイルを web/views/error_view.ex に生成します。テンプレートのデフォルトのコンテンツはGithubにあります。

また、カスタム エラーに関するドキュメントも参照MyApp.ErrorsViewしてください。MyApp.ErrorView

于 2015-02-21T08:03:37.390 に答える
0

plug :accepts, ["json"]in you で400-500 エラーをオーバーライドできますrouter.ex。例えば:

# config/config.exs
...
config :app, App.endpoint,
  ...
  render_errors: [accepts: ~w(html json)],
  ...    

# web/views/error_view.ex
defmodule App.ErrorView do
 use App.Web, :view

 def render("404.json", _assigns) do
   %{errors: %{message: "Not Found"}}
 end

 def render("500.json", _assigns) do
   %{errors: %{message: "Server Error"}}
 end
end


# in router.ex
defmodule App.Router do
 use App.Web, :router

 pipeline :api do
   plug :accepts, ["json"]
 end

 pipe_through :api

 # put here your routes
 post '/foo/bar'...

 # or in scope: 
 scope '/foo' do
   pipe_through :api
   get 'bar' ...
 end

それは動作します。

于 2016-03-22T05:17:58.600 に答える