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

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
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 126479 1222
New

We're in Beta

About us Mission Statement