在Phoenix应用程序中设置异常的自定义响应 [英] Setting up custom response for exception in Phoenix Application

查看:99
本文介绍了在Phoenix应用程序中设置异常的自定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ecto编写phoenix应用程序,并在测试中包含以下代码段

im writing phoenix application with ecto and have the following snippet in the test

{:ok, data} = Poison.encode(%{email: "nonexisting@user.com", password: "mypass"})

conn()
|> put_req_header("content-type", "application/json")
|> put_req_header("accept", "application/json")
|> post(session_path(@endpoint, :create), data)
> json_response(:not_found) == %{}

这会引发Ecto.NoResultsError

this throws a Ecto.NoResultsError

我有这个定义

defimpl Plug.Exception, for: Ecto.NoResultsError do
  def status(_exception), do: 404
end

但是测试仍然会引发Ecto.NoResultsError,是否有任何指针?

but the test still throws Ecto.NoResultsError, Any pointers?

推荐答案

让我们考虑一下每种环境下的工作原理.

Let's consider how it works per environment.

  • :prod中,默认设置是呈现错误页面,因此您应该看到由YourApp.ErrorView呈现的带有状态代码的页面;

  • In :prod, the default is to render error pages, so you should see a page rendered by YourApp.ErrorView with the status code;

:dev中,默认设置是显示调试页,因为大多数情况下在构建代码时都会出错.如果要查看实际显示的错误页面,则需要在config/dev.exs;

In :dev, the default is to show debug pages, because the majority of times you have an error while building your code. If you want to see the actually rendered error page, you need to set debug_errors: false in your config/dev.exs;

:test中,它的工作方式类似于生产,但是由于您是从测试中调用应用程序,因此如果应用程序崩溃,测试也将崩溃.我们在将来的版本中对此进行了改进,您应该可以在其中编写类似以下内容的内容:

In :test, it works like production but, because you are calling your application from the test, your test will also crash if your application crashes. We are improving this on future versions, where you should be able to write something like:

assert_raise Ecto.NoResultsError, fn ->
  get conn, "/foo"
end
{status, headers, body} = sent_response(conn)
assert status == 404
assert body =~ "oops"

这篇关于在Phoenix应用程序中设置异常的自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆