如何覆盖凤凰城的错误?

时间:2015-02-21 00:39:16

标签: elixir phoenix-framework

我在凤凰上建立了宁静的api(json)。而且我不需要html的支持。

如何覆盖凤凰城的错误?示例错误: - 500 - 404没有找到路线时 和其他。

4 个答案:

答案 0 :(得分:6)

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 {form} and render("404.json", _assigns) to your app's render("500.json", _assigns) file.

For example:

web/views/error_view.ex

Then in your 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 file updated the config/config.exs to 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.

答案 1 :(得分:4)

您需要自定义MyApp.ErrorView。 Phoenix在web / views / error_view.ex中为您生成此文件。可以找到模板的默认内容on Github

另请参阅the docs on custom errors,虽然它们似乎有点过时,因为它们会指示您使用MyApp.ErrorsView(复数),后者已替换为MyApp.ErrorView

答案 2 :(得分:0)

您可以使用plug :accepts, ["json"]中的router.ex覆盖400-500个错误。例如:

# 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

它会起作用。

答案 3 :(得分:0)

以上答案对我都不起作用。 我只能使phoenix仅对api端点使用json的唯一方法是以这种方式编辑端点设置:

config :app, App.Endpoint,
       render_errors: [
         view: App.ErrorView,
         accepts: ~w(json html) # json has to be in before html otherwise only html will be used
       ]

使用json的想法必须是要呈现的html的世界列表中的第一个,虽然有点奇怪,但它确实可行。

然后有一个如下所示的ErrorView:

defmodule App.ErrorView do
  use App, :view

  def render("400.json", _assigns) do
    %{errors: %{message: "Bad request"}}
  end

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

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

与这里的其他答案没有什么不同,我只是添加了一个400错误的请求,因为我遇到了,您也应该这样做:添加可能遇到的任何内容。

最后在我的路由器代码中:

pipeline :api do
  plug(:accepts, ["json"])
end
pipeline :browser do
  plug(:accepts, ["html"])
  ...
end

与其他答案没什么不同,但您必须确保管道配置正确。