Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match Ecto query error

Tags:

elixir

ecto

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?

like image 578
Dania_es Avatar asked Apr 11 '15 17:04

Dania_es


People also ask

How does SQL pattern matching work?

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.

What is an ecto query?

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.

Are ecto queries composable if there is no schema?

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.

Does ecto always match the source given in from?

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.


2 Answers

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).

like image 77
José Valim Avatar answered Sep 27 '22 18:09

José Valim


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

like image 26
Philip Avatar answered Sep 27 '22 19:09

Philip