我正在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中将其返回给客户端? 有没有一种干净的方法可以做到这一点?