How do you get error of Repo.all on pattern machine

ecto

#1

Hello , how do you get error of Repo.all on pattern machine?

My code is:

	def join(age) do
		query = from p in UsersInfo,
          join: c in EditUserHistory, 
          where: c.users_info_id == p.id,
          where: p.age > ^age,
          select: %{full_name: p.full_name, email: c.old_email}
 
		Repo.all(query)
	end

I have big error when I send invalid params , like this :

iex(15)> TrangellUsersService.Login.Db.UsersInfoQuery.join "test"
** (Ecto.Query.CastError) apps/trangell_users_service/lib/trangell_users_service/login/db/usersquery.ex:12: value `"test"` in `where` cannot be cast to type :integer in query:

from u in TrangellUsersService.Login.Db.UsersInfo,
  join: e in TrangellUsersService.Login.Db.EditUserHistory,
  on: true,
  where: e.users_info_id == u.id,
  where: u.age > ^"test",
  select: %{full_name: u.full_name, email: e.old_email}

    (elixir) lib/enum.ex:1829: Enum."-reduce/3-lists^foldl/2-0-"/3
    (elixir) lib/enum.ex:1375: Enum."-map_reduce/3-lists^mapfoldl/2-0-"/3
    (elixir) lib/enum.ex:1375: Enum."-map_reduce/3-lists^mapfoldl/2-0-"/3
    (elixir) lib/enum.ex:1829: Enum."-reduce/3-lists^foldl/2-0-"/3
    (ecto) lib/ecto/repo/queryable.ex:124: Ecto.Repo.Queryable.execute/5
    (ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (iex) lib/iex/evaluator.ex:231: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:212: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:190: IEx.Evaluator.eval/3

how do I get error on pattern ? like this ?

case join("os") do
  [] -> IO.puts "hi"
  [item] ->  IO.puts "by"
end

I have read the document , but I didn’t understand .

https://hexdocs.pm/ecto/Ecto.Repo.html#c:all/2

May raise Ecto.QueryError if query validation fails.


#2

Maybe a guard clause would help?

   def join(age) when is_number(age) do
		query = from p in UsersInfo,
          join: c in EditUserHistory, 
          where: c.users_info_id == p.id,
          where: p.age > ^age,
          select: %{full_name: p.full_name, email: c.old_email}
 
		Repo.all(query)
	end

#3

thank you , but how do I get error in my code without guard ?


#4

You can wrap it in a try / catch block.

def join(age) do
  query = from p in UsersInfo,
    join: c in EditUserHistory, 
    where: c.users_info_id == p.id,
    where: p.age > ^age,
    select: %{full_name: p.full_name, email: c.old_email}
 
  Repo.all(query)
rescue
  e in Ecto.Query.CastError -> {:error, :cast_error}
else
  results -> {:ok, results}
end