gpt4 book ai didi

elixir - (RuntimeError) 预期 action/2 返回一个 Plug.Conn,所有的 Plugs 都必须接收一个连接 (conn) 并返回一个连接

转载 作者:行者123 更新时间:2023-12-01 11:24:31 34 4
gpt4 key购买 nike

在我的一个 Controller 中,我有以下代码(摘录):

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

我究竟做错了什么?

最佳答案

堆栈跟踪告诉您您的 Controller 操作没有返回 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

关于elixir - (RuntimeError) 预期 action/2 返回一个 Plug.Conn,所有的 Plugs 都必须接收一个连接 (conn) 并返回一个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834696/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com