arcyfelix
Hi.
I am creating a simple user CRUD with Phoenix 1.4 (App is called simply Backend).
Each user must have an email and a password. The email MUST be unique.
I expressed that in the migration and the schema:
- priv/repo/migrations/20190530142317_create_users.exs
defmodule Backend.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :email, :string, null: false, unique: true
add :password, :string, null: false
add :is_active, :boolean, default: false, null: false
timestamps()
end
create unique_index(:users, [:email])
end
end
- lib/backend/auth/user.ex
defmodule Backend.Auth.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :email, :string, null: false, unique: true
field :password, :string, null: false
field :is_active, :boolean, default: true
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:email, :password, :is_active])
|> validate_required([:email])
|> unique_constraint(:email, name: :users_email_index)
end
end
My problem is that when the validation fails, all I get is:
{
"errors": {
"detail": "Internal Server Error"
}
}
I worked around one error (unique email address) as follows:
- lib/backend_web/controllers/user_controller.ex
defmodule BackendWeb.UserController do
use BackendWeb, :controller
alias Backend.Auth
alias Backend.Auth.User
action_fallback BackendWeb.FallbackController
def index(conn, _params) do
users = Auth.list_users()
render(conn, "index.json", users: users)
end
def create(conn, %{"user" => user_params}) do
case Auth.create_user(user_params) do
{:ok, %User{} = user} ->
conn
|> put_status(:created)
|> put_resp_header("location", Routes.user_path(conn, :show, user))
|> render("show.json", user: user)
{:error, %Ecto.Changeset{} = changeset} ->
case changeset.errors do
[{:email, _}] ->
conn
|> send_resp(409, "User already exists!")
end
end
end
def show(conn, %{"id" => id}) do
user = Auth.get_user!(id)
render(conn, "show.json", user: user)
end
def update(conn, %{"id" => id, "user" => user_params}) do
user = Auth.get_user!(id)
with {:ok, %User{} = user} <- Auth.update_user(user, user_params) do
render(conn, "show.json", user: user)
end
end
def delete(conn, %{"id" => id}) do
user = Auth.get_user!(id)
with {:ok, %User{}} <- Auth.delete_user(user) do
send_resp(conn, :no_content, "")
end
end
end
However, I would need to write a lot of functions and cases to return a meaningful message and I am sure the Phoenix team already solved it in a smart way.
For reference, I add following files:
- lib/backend_web/controllers/fallback_controller.ex
defmodule BackendWeb.FallbackController do
@moduledoc """
Translates controller action results into valid `Plug.Conn` responses.
See `Phoenix.Controller.action_fallback/1` for more details.
"""
use BackendWeb, :controller
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(BackendWeb.ErrorView)
|> render(:"404")
end
end
- lib/backend_web/views/error_view.ex
defmodule BackendWeb.ErrorView do
use BackendWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
Thank you!
PS. I already love Phoenix! Keep up the great work, Core Team!
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 4 to 1- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
arcyfelix
Ok, I will post my issue for sake of others that might have a similar problem.
I must have deleted following piece of code from my fallback_controller.ex:
Thank you all for help, the topic can be closed.
arcyfelix
Yes, I know.
That was a quick and dirty trick.
Thanks, I will have a try.
wojtekmach
do you have more than 1 error? If so,
[{:email, _}]won’t match changeset.errors and maybe that’s why you’re getting a 500.I’d recommend seeing how Phoenix does it with generated CRUD using
mix phx.gen.html Blog Post posts title:string.lpil
Is there an error message printed in the log?