Like other functions in elixir (as well as Ecto's own transactions), I want to pattern match to handle potential errors with Ecto queries. Like this:
case Repo.get!(User, id) do
{:ok, user} ->
#do something
{:error, message} ->
#pass the error
end
Obviously this does not work, but how can I pattern match Ecto errors like Ecto.NotSingleResult and other potential query problems like preload errors?
Below is the working of SQL Pattern Matching: The pattern with which we have to match the expression can be a sequence of the regular characters and wildcard characters. The wildcard characters provide flexibility and variety in matching the expressions.
Queries are used to retrieve and manipulate data from a repository (see Ecto.Repo ). Ecto queries come in two flavors: keyword-based and macro-based.
In any case, regardless if a schema has been given or not, Ecto queries are always composable thanks to its binding system. On the left-hand side of in we specify the query bindings.
As long as the number of bindings is less than the number of from s + join s, Ecto will match only what you have specified. The first binding always matches the source given in from.
Use Repo.get
which will return a value or nil. You can then pattern match on the expected struct or use if-clauses. Repo.get!
raises on purpose (for the cases you expect a struct to be there and not being there is an error).
This might do the trick
case Repo.get(User, id) do
user when is_map(user) -> {:ok, user}
nil -> {:error, "not found"}
end
Reffering to this Elixir, Ecto pattern matching conditional with db query not behaving as expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With