shahryarjb
How to stop 500 errors when UUID doesn't match
I have an 500 error when my user changes UUID which is relation to Category UUID for inserting post.
** (exit) an exception was raised:
** (Ecto.ChangeError) value `"a863228-727c-4cf3-93f5-9b2f79df1288"` for `TrangellCmsService.Cms.Db.Post.cms_post_category_id` in `insert` does not match type :binary_id
How do I prevent an 500 error in client request? I want to show 400 error instead of 500 error , how do ?
my changeset :
def changeset(struct, params \\ %{}) do
struct
|> cast(params, @all_fields)
|> validate_required(@all_fields)
|> unique_constraint(:seo_alias_link, name: :index_of_post_alias_unique_link, message: "alias link already exists.")
|> validate_inclusion(:seo_language, ["en", "fa"])
|> validate_inclusion(:group_acl, ["admin", "actived", "unactived", "blocked"])
|> validate_inclusion(:post_type, ["article", "shop", "free"])
|> validate_length(:title, min: 3, max: 100)
|> validate_length(:description, min: 100)
|> validate_length(:seo_words, min: 3, max: 100)
|> validate_length(:seo_description, min: 50, max: 264)
|> foreign_key_constraint(:cms_post_category_id)
end
Most Liked
rwngallego
In Ecto3 when you specify in your model the primary key you can use Ecto.UUID instead of :binary_id so that the Ecto casting works correctly:
@primary_key {:id, Ecto.UUID, autogenerate: true}
schema "post" do
...
end
This way you should get the regular Ecto validations before going to the DB which looks like is what you want: {"id":"is invalid"}
From the ecto documentation:
… (typically
:idor:binary_id, but can be any type)
kokolegorille
Maybe You can test like this
iex> Ecto.UUID.cast "a863228-727c-4cf3-93f5-9b2f79df1288"
:error
iex> Ecto.UUID.cast Ecto.UUID.bingenerate()
{:ok, "767f998a-424b-4270-beff-742b93f636fc"}
Ankhers
It also depends on the properties you want your program to have. In this specific case I would prefer to return an error to the client saying that the UUID specified is invalid.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex










