theagilecoder

theagilecoder

I used mix phx.gen.json to generate a simple User resource. Among the files it generated, two of them are

user_controller.ex

defmodule MyapiWeb.UserController do
  use MyapiWeb, :controller

  alias Myapi.Accounts
  alias Myapi.Accounts.User

  action_fallback MyapiWeb.FallbackController

  def index(conn, _params) do
    users = Accounts.list_users()
    render(conn, "index.json", users: users)
  end

  def create(conn, %{"user" => user_params}) do
    with {:ok, %User{} = user} <- Accounts.create_user(user_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.user_path(conn, :show, user))
      |> render("show.json", user: user)
    end
  end

  def show(conn, %{"id" => id}) do
    user = Accounts.get_user!(id)
    render(conn, "show.json", user: user)
  end

  def update(conn, %{"id" => id, "user" => user_params}) do
    user = Accounts.get_user!(id)

    with {:ok, %User{} = user} <- Accounts.update_user(user, user_params) do
      render(conn, "show.json", user: user)
    end
  end

  def delete(conn, %{"id" => id}) do
    user = Accounts.get_user!(id)

    with {:ok, %User{}} <- Accounts.delete_user(user) do
      send_resp(conn, :no_content, "")
    end
  end
end

and fallback_controller.ex

defmodule MyapiWeb.FallbackController do
  @moduledoc """
  Translates controller action results into valid `Plug.Conn` responses.

  See `Phoenix.Controller.action_fallback/1` for more details.
  """
  use MyapiWeb, :controller

  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    IO.inspect(changeset)
    conn
    |> put_status(:unprocessable_entity)
    |> put_view(MyapiWeb.ChangesetView)
    |> render("error.json", changeset: changeset)
  end

  def call(conn, {:error, :not_found}) do
    conn
    |> put_status(:not_found)
    |> put_view(MyapiWeb.ErrorView)
    |> render(:"404")
  end
end

My question is regarding the def call(conn, {:error, :not_found}) function in fallback_controller.ex. When it is called ?

  • When a User is created or updated which is not valid, def call(conn, {:error, %Ecto.Changeset{} = changeset}) is called. I know how fallback with with works.

  • When show or delete function in user_controller.ex is called with the wrong user_id, Ecto.NoResultsError is converted to 404 response.

So, what is the point of def call(conn, {:error, :not_found}) function in fallback_controller.ex ? When is it called ?

Showing Posts 1 to 10

hauleth

hauleth

call in fallback module will be called when you return non-Plug.Conn value from your controller function. In this case it can happen in 2 places:

  • if the Accounts.create_user/1 fails to return {:ok, %User{}}
  • if the Accounts.update_user/2 fails to return {:ok, %User{}}
theagilecoder

theagilecoder OP

Yes I know how fallback controlller works but Accounts.create_user/1 and Accounts.update_user/2 will either return {:ok, %User{}} or {:error, %Ecto.Changeset{}}. When would they return {:error, :not_found} ?

lpil

lpil

Creator of Gleam

It would be called if you write Context.get_thing in another controller action when using with. It’s a common pattern so Phoenix supports it.

theagilecoder

theagilecoder OP

When you say it, do you mean call(conn, {:error, %Ecto.Changeset{} = changeset}) or call(conn, {:error, :not_found}) ?

lpil

lpil

Creator of Gleam

Both. Phoenix includes a set of common fallback patterns out of the box, and you may choose to add more.

theagilecoder

theagilecoder OP

Please read my post again. I know how fall back works. Both will not be called for the same req. Either call(conn, {:error, %Ecto.Changeset{} = changeset}) will be called or call(conn, {:error, :not_found}). I Know when call(conn, {:error, %Ecto.Changeset{} = changeset}) gets called. I dont know when call(conn, {:error, :not_found}) gets called.

kokolegorille

kokolegorille

You don’t need to yell…

hauleth

hauleth

It is called when you return {:error, :not_fount} from the handler. I have no idea when you do that, but when you will, then it will be called. There is no magic there. You are author of the code above, not us, so we cannot tell you when you return what value from the functions and my crystal ball broke last week, so I cannot look into your code, sorry.

theagilecoder

theagilecoder OP

Apologies, not my intention.

josevalim

josevalim

Creator of Elixir

You are correct. It is not used by default. Please open up an issue: we should either remove it or add a code comment to it.

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
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
JesseHerrick
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews