简体   繁体   English

Elixir错误处理管道选项

[英]Elixir error handling pipe options

The following code is an invalid changeset which errors, however it took me a long time to find the cause because the error message was not originally being matched and logged. 以下代码是一个无效的变更集,发生了错误,但是我花了很长时间才找到原因,因为错误消息最初并未被匹配和记录。

I added a case statement to the end of the pipe, is this the best way to pickup errors in pipes? 我在管道末尾添加了一个case语句,这是消除管道中错误的最好方法吗?

    User.changeset(%User{}, %{username: "username_is_test", password: "test", password_confirmation: "test", email: "test@test.com"})
    |> Repo.insert
    |> case  do
        {:ok, result} -> IO.puts("result")
        {:error, error} -> IO.inspect error
    end

Pipelines and error tuples don't work very well together. 管道和错误元组不能很好地协同工作。 You can handle an error at the end of a pipeline with a case as you have, but it only works at the last stage. 您可以根据需要在case的流水线末端处理错误,但仅在最后阶段有效。

For operations returning error tuples, I prefer to use with / else syntax: 对于返回错误元组的操作,我更喜欢使用with / else语法:

with changeset <- User.changeset(%User{}, %{username: "username_is_test", password: "test", password_confirmation: "test", email: "test@test.com"})
     {:ok, result} <- Repo.insert(changeset) do
  IO.puts("result")
else
  {:error, error} -> IO.inspect error
end

You can add as many failable operations as required in the with block, and handle all the error cases with pattern matching in the else block. 您可以根据需要在with块中添加尽可能多的失败操作,并在else块中使用模式匹配来处理所有错误情况。

https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1 https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1

You have a couple options. 您有两种选择。 If you don't want to explicitly handle the error conditions, you should use Repo.insert! 如果您不想显式处理错误情况,则应使用Repo.insert! instead. 代替。 At least this will raise an exception if the changeset is not valid. 如果变更集无效,至少这将引发异常。

Otherwise, you should be using a case handle handling the {:error, changeset} by checking the changeset.action in your template. 否则,您应该通过检查模板中的changeset.action来使用处理{:error, changeset}的案例句柄。

In more complicated pipelines that can error part way through, I've started using the with special form. 在可能会部分出错的更复杂的管道中,我开始with特殊形式使用。

with result when not is_nil(result) <- fun1, 
     {:ok, result} <- fun2(result), 
     {:ok, result} <- fun3(result) do
  success_handling(result)
else
  nil -> # handle first failure
  {:error, error} -> # handle other errors
  _ -> # catch all failure
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM