Can I use the Phx 1.3 FallbackController with functions that are no traditional actions?

I am trying to get the generated FallbackController working with a function which is not a classical “action” but It just won’t work. No I am wondering: Is this even intended?

This is what I do:

defmodule ApiWeb.AuthController do
  use ApiWeb, :controller
  plug(Ueberauth)

  alias Api.Accounts
  alias Api.Accounts.User

  action_fallback(ApiWeb.FallbackController)

  ....
 # The return of this function should trigger the FallbackController if an error occurs. 
  def register_user(conn, :identity, auth) do
    with {:ok, result} <- Accounts.create_user(:identity, auth) do
      # Encode a JWT
      {:ok, jwt, _} = Api.Guardian.encode_and_sign(result.user)

      # Return token to client
      conn
      |> put_status(:created)
      |> put_resp_header("authorization", "Bearer #{jwt}")
      |> json(%{access_token: jwt})
    end
  end
...

In my FallbackController I added this call function:

  def call(conn, {:error, :identity_representation, changeset, _}) do
    conn
    |> put_status(:unprocessable_entity)
    |> render(ApiWeb.ChangesetView, "error.json-api", changeset: changeset)
  end

But the call never gets called. Is there some way to use the FallbackController with some conventional function?

1 Like

Where is register_user/3 called from? action_fallback only works agains the controller action. So your fallback controller will only be invoked in the controller action fails to return a %Plug.Conn{}. If your action invoked register_user/3 then it would work

2 Likes

Hey Chris, thank you for your answer and for the amazing phoenix framework!

register_user/3 is called in this action:

  def callback(%{assigns: %{ueberauth_auth: auth}} = conn, %{"provider" => provider}) do
    case AuthUser.basic_info(String.to_atom(provider), auth) do
      {:login, user} ->
        authenticate_user(conn, %{"auth" => auth, "provider" => provider})

      {:registration, user} ->
        register_user(conn, String.to_atom(provider), auth)
    end
  end