phoenix で安らかな API (json) をビルドします。そして、html のサポートは必要ありませんでした。
フェニックスのエラーをオーバーライドするには? エラー例: - 500 - ルートが見つからない場合の 404 など。
phoenix で安らかな API (json) をビルドします。そして、html のサポートは必要ありませんでした。
フェニックスのエラーをオーバーライドするには? エラー例: - 500 - ルートが見つからない場合の 404 など。
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.
をカスタマイズする必要がありますMyApp.ErrorView。Phoenix はこのファイルを web/views/error_view.ex に生成します。テンプレートのデフォルトのコンテンツはGithubにあります。
また、カスタム エラーに関するドキュメントも参照MyApp.ErrorsViewしてください。MyApp.ErrorView
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
それは動作します。