flash4syth

flash4syth

How can I handle a 401 error for my JSON API? Currently I’m handling it like this in my Controller:

 conn
        |> put_resp_content_type("application/json")
        |> send_resp(401, Jason.encode!("Not Authorized"))
        |> halt()

but I would like to just call something like render(conn, "401.json") and have it be handled in the lib/<myapp_web>/views/error_view.ex module as 404 and 500 errors are. I know this is what happens on Ecto.NoResultsError, the function render("404.json", conn) is called in error_view.ex. It looks like I can do it with a custom error from these docs: https://hexdocs.pm/phoenix/errors.html but I’m missing some details on how to do that. I’m not sure if that is the best way to DRY up my code anyways.

Thanks!

Showing Posts 1 to 3

outlog

outlog

I use the fallback controller.. and then just let the controller return {:error, :unauthorized } when needed - so the controller is nice and DRY

defmodule Myapp.Web.SomeController do
  ...
  action_fallback(Myapp.Web.FallbackController)


  def show(conn, params) do
   user = SomeAuth.get_user(params)
   if user do
     render normal etc..
   else
     {:error, :unauthorized }
   end 
  end
end

and fallback has:

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

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

...

  def call(conn, {:error, :unauthorized}) do
    conn
    |> put_status(:unauthorized)
    |> render(Myapp.Web.ErrorView, "auth_required.json")
  end
end

and the ErrorView has a

  def render("auth_required.json", _assigns) do
    %{error: "Unauthorized"}
  end
flash4syth

flash4syth OP

@outlog that solution is nice, it works. The only issue I have with it is the deprecation warning I get when I run my tests:

Elixir.Phoenix.Controller.render/4 with a view is deprecated, see the documentation for render/3 for an alternative
flash4syth

flash4syth OP

Ok, I used your solution with a slight modification to the FallbackController in order to prevent the deprecation warning:

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

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

...

  def call(conn, {:error, :unauthorized}) do
    conn
    |> put_status(:unauthorized)
    |> put_view(Myapp.Web.ErrorView)
    |> render("auth_required.json")
  end
end

Thank you for the help!

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
widianto
I think I’ve found a small improvement I could contribute to &lt;%= web_namespace %&gt;.CoreComponents (installer/templates/phx_web/compo...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews