在我的一个控制器中,我有以下代码(摘录):
case HTTPoison.get("https://*****.zendesk.com/api/v2/users/search.json?query=" <> clid, headers, [hackney: hackney]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
conn
|> put_status(200)
|> json(body)
{:ok, %HTTPoison.Response{status_code: 404}} ->
conn
|> put_status(404)
|> json(%{error_code: "404", reason_given: "Resource not found."})
{:error, %HTTPoison.Error{reason: reason}} ->
conn
|> put_status(500)
|> json(%{error_code: "500", reason_given: "None."})
end
当我运行代码时,它工作正常,但Phoenix抛出运行时异常:
** (exit) an exception was raised:
** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection
(zentonies) web/controllers/page_controller.ex:1: Zentonies.PageController.phoenix_controller_pipeline/2
(zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.instrument/4
(zentonies) lib/phoenix/router.ex:261: Zentonies.Router.dispatch/2
(zentonies) web/router.ex:1: Zentonies.Router.do_call/2
(zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.phoenix_pipeline/1
(zentonies) lib/plug/debugger.ex:93: Zentonies.Endpoint."call (overridable 3)"/2
(zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
我做错了什么?
答案 0 :(得分:3)
堆栈跟踪告诉您控制器操作未返回Plug.Conn
结构。在Elixir中,返回函数最后一个表达式的结果。查看函数的最后一行并确保它返回case表达式的结果。
def(conn, params) do
final_conn =
case HTTPoison.get("https://*****.zendesk.com/api/v2/users/search.json?query=" <> clid, headers, [hackney: hackney]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
conn
|> put_status(200)
|> json(body)
{:ok, %HTTPoison.Response{status_code: 404}} ->
conn
|> put_status(404)
|> json(%{error_code: "404", reason_given: "Resource not found."})
{:error, %HTTPoison.Error{reason: reason}} ->
conn
|> put_status(500)
|> json(%{error_code: "500", reason_given: "None."})
end
do_something_else(params)
final_conn
end