I am working with simple phoenix elixir application. In this app I'm trying to expose a rest api to save and retrieve data.
In my case, if the primary key (email address ) is a duplicate, my application throws an error. I need to know the best way to handle this error; either try-catch or any other better solutions.
this is my data save method
def post(conn, %{"stooge" => stooge, "name" => name, "email" => email , "password" => password})do
respond = Repo.insert!(%ApiDb.User{name: name, email: email, stooge: stooge, password: password})
json conn, respond
end
sample payload
{
"stooge": "moe",
"name": "Joe",
"email": "[email protected]",
"password":"asdasd"
}
models/user.ex
defmodule ApiDb.User do
use ApiDb.Web, :model
schema "users" do
field :password, :string
field :name, :string
field :email, :string
field :stooge, :string
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :email, :password, :stooge])
|> validate_required([:name, :email, :password])
|> validate_format(:email, ~r/@/)
end
end
I tried the try-catch blocks but there was no luck
try do
respond = Repo.insert!(%ApiDb.User{name: name, email: email, stooge: stooge, password: password})
json conn, respond
rescue
e in Ecto.ConstraintError -> IO.puts("An error occurred: ")
end
changeset
function inApiDb.User
, addunique_constraint
to it as the error message says, and then useRepo.insert
in the controller withcase
to handle the error case. Try generating a model withphoenix.gen.json
in a brand new app and study its source or read phoenixframework.org/docs/ecto-models (especiallycase Repo.insert(changeset) do ...
on that page). – Dogbert