拯救 Ecto.ConstraintError 以保持迁移滚动?
Rescuing an Ecto.ConstraintError to keep a migration rolling?
如何挽救 Ecto.ConstraintError(由唯一性冲突引起 - 我在名为 "field" 的字符串 属性 上有一个唯一索引)
这是我的代码,它仍在引发错误并且似乎无法挽救 - ecto.migration 停止:
try do
Repo.insert(model_changeset, on_conflict: :nothing)
rescue
e -> IO.puts(inspect e)
end
还有一件事要注意——有时 model_changeset 不是一个变更集而是一个结构——我应该总是传递一个变更集吗?我假设使用 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 (https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3),它基本上将数据库错误变成了变更集错误。
那你就可以用case语句了
case Repo.insert(model_changeset) do
{:ok, schema} -> schema
{:error, changeset} -> IO.inspect changeset
end
如何挽救 Ecto.ConstraintError(由唯一性冲突引起 - 我在名为 "field" 的字符串 属性 上有一个唯一索引)
这是我的代码,它仍在引发错误并且似乎无法挽救 - ecto.migration 停止:
try do
Repo.insert(model_changeset, on_conflict: :nothing)
rescue
e -> IO.puts(inspect e)
end
还有一件事要注意——有时 model_changeset 不是一个变更集而是一个结构——我应该总是传递一个变更集吗?我假设使用 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 (https://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3),它基本上将数据库错误变成了变更集错误。
那你就可以用case语句了
case Repo.insert(model_changeset) do
{:ok, schema} -> schema
{:error, changeset} -> IO.inspect changeset
end