Catching Ecto.CastError with action_fallback

Good Day!

Was toying around with phoenix trying to make an API and came across with Ecto.Query.CastError:

[debug] ** (Ecto.Query.CastError) deps/ecto/lib/ecto/repo/queryable.ex:322: 
           value `"112sd"` in `where` cannot be cast to type :id in query:

         from u in PhxTest.Account.User,
         where: u.id == ^"112sd",
         select: u

I know this is a silly error , I am trying to have a string as a params of Repo.get(). Now my question is how would one can use the action_fallback to catch this kind of error and return a custom error. Please help me :cry: :smiley:

1 Like

action_fallback is about handling different return values of a function, and that’s an exception. The https://hexdocs.pm/plug/Plug.Exception.html#content Plug exception protocol could perhaps be used to catch that error and return a 400, but really this would be better handled by some form of input validation.

1 Like

To add on top of @benwilson512 answer, phoenix_ecto already implements Phoenix.Exception for Ecto.Query.CastError [1]. But yeah, agreed it would be nicer to catch invalid input earlier in processing.

[1] https://github.com/phoenixframework/phoenix_ecto/blob/v3.2.3/lib/phoenix_ecto/plug.ex#L5

3 Likes

Alright, Thanks for the answers. I’ll toying with this again :smile: .
Thanks @benwilson512 & @wojtekmach