flash4syth

flash4syth

Handle 401 error for JSON API

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!

Marked As Solved

flash4syth

flash4syth

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!

Also Liked

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

Where Next?

Popular in Questions Top

hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 131117 1222
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New

We're in Beta

About us Mission Statement