Postgrex.Error exception handling

defmodule DB_API do
  alias TheDB.{Repo}
  import Ecto.Query

  def delete_single_record(table_name, key_atom, identifier) do
    try do
      Repo.transaction(fn ->
        from(record in table_name,
          where: field(record, ^key_atom) == ^identifier
        )
        |> Repo.delete_all()
      end)
    catch
      Postgrex.Error -> delete_single_record(table_name, key_atom, identifier)
    end
  end
end

** Reason for termination == , ** {#{'__exception__' => true,'__struct__' => 'Elixir.Postgrex.Error',connection_id => nil,message => nil,postgres => #{code => serialization_failure,detail => <<"Reason code: Canceled on identification as a pivot, during commit attempt.">>,file => <<"predicate.c">>,hint => <<"The transaction might succeed if retried.">>,line => <<"4853">>,message => <<"could not serialize access due to read/write dependencies among transactions">>,pg_code => <<"40001">>,routine => <<"PreCommit_CheckForSerializationFailure">>,severity => <<"ERROR">>,unknown => <<"ERROR">>},query => nil},[{'Elixir.DBConnection',run_transaction,4,[{file,"lib/db_connection.ex"},{line,1547}]},{'Elixir.DB_API',delete_single_record,3,[{file,"lib/Helper Modules/DB_API.ex"},{line,72}]}

Why is this exception not being caught by the try/catch block?

You probably want to use rescue instead of catch

2 Likes