REST API自定义MatchError优雅地处理

我正在Elixir中使用REST API。我正在尝试设计一个系统,使我无法通过模式匹配将自定义消息返回给客户端。我正在使用Plug。

假设我有一个在数据库中创建用户的端点,如果帐户已经存在,我可能会使以下语句失败:
0 = DbAdapter.select("SELECT * FROM users WHERE email = 'email@example.com';)

此操作失败,并显示MatchError,并且插件将通用Internal server error返回给客户端。

我想做的是定义一些类似以下的结构:

0 = DbAdapter.select("...") << %{code: 1113,reason: "account already exists"}

基本上,如果断言0 = DbAdapter.select("...")失败,我想将%{code: 1113,reason: "account already exists"}返回给客户端。我的目标是真正简单的语法,例如上面的语法(可能是运算符重载之类的东西)。

我的理解是,插件通过以下方法处理错误:

def handle_errors(conn,ree = %{kind: _kind,reason: _reason,stack: _stack}) do
    IO.inspect ree
    send_resp(conn,conn.status,"Internal error: The resource you're looking for might not exist on the server.")
end

如何在断言失败时获取自定义错误元组,并在handle_errors中将其返回给客户端? 有没有一种干净的方法可以做到这一点?

erma001 回答:REST API自定义MatchError优雅地处理

Story.append(Paragraph("Whatever printed with yourStyle",yourStyle)) 用于处理请求中可能发生的错误,而不是根据操作结果返回的一种特殊状态。

您需要创建自己的应用程序以返回有效数据,或者创建有意义的错误代码,以从中生成适合客户端的响应:

handle_errors

在其他地方,也许在另一个插件中:

case DbAdapter.select("...") do
  0 -> create!
  _ -> %{code: 1113,reason: "account already exists"}
end
本文链接:https://www.f2er.com/3134058.html

大家都在问