Elixir 营救一个外星人,让他们继续迁移?
如何拯救一个exto.ConstraintError(由唯一性冲突引起-我在一个名为“field”的字符串属性上有一个唯一的索引) 以下是我所拥有的代码,它仍在引发错误,似乎无法挽救-exto.migration停止:Elixir 营救一个外星人,让他们继续迁移?,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,如何拯救一个exto.ConstraintError(由唯一性冲突引起-我在一个名为“field”的字符串属性上有一个唯一的索引) 以下是我所拥有的代码,它仍在引发错误,似乎无法挽救-exto.migration停止: try do Repo.insert(model_changeset, on_conflict: :nothing) rescue e -> IO.puts(inspect e) end 另一件需要注意的事情——有时mode
try do
Repo.insert(model_changeset, on_conflict: :nothing)
rescue
e -> IO.puts(inspect e)
end
另一件需要注意的事情——有时model_变更集不是变更集,而是结构——我应该始终传递变更集吗?我假设有了rescue条款就没关系了——我应该能够按照我指定的方式对任何一般错误进行补救
编辑:
以下是相关的错误消息:
%Ecto.ConstraintError{constraint: "cars_field_index", message: "constraint error when attempting to insert struct:\n\n * unique: claims_name_index\n\nIf you would like to convert this constraint into an error, please\ncall unique_constraint/3 in your changeset and define the proper\nconstraint name. The changeset has not defined any constraint.\n", type: :unique}
** (DBConnection.ConnectionError) transaction rolling back
将惟一约束添加到变更集unique_constraint/3(),它基本上将数据库错误转化为变更集错误 然后,您可以使用case语句
case Repo.insert(model_changeset) do
{:ok, schema} -> schema
{:error, changeset} -> IO.inspect changeset
end
请分享错误消息。@mudasobwa-添加了约束消息错误消息所说的正是@MartinElvar在回答中提出的。@mudasobwa,我不应该仍然能够从错误中拯救/恢复吗?我认为拯救一个常规异常意味着你不需要添加“unique\u constraint”来将错误转换成状态元组……呃。。。事实上,人们应该能够
营救*confusedI在变更集中添加了一个独特的_约束,这是一个令人困惑的问题。您可以发布您的变更集函数,并在迁移中添加约束吗?:)嗨,Martin,如果我没记错的话,我想这是因为我在变更集中没有足够的唯一约束,所以我会把你的标记为答案。