whoiswentz

whoiswentz

Middleware like plug

Sup guys.

I’m running into a problem and doubt, I need to create a Plug that runs after the Router, basically, I have a controller that throws an exception eg. Ecto.NoResultsError, I need to catch this error using a plug, handle it and return a JSON to the client.

Marked As Solved

tfwright

tfwright

Why is the error reraising is undesirable for your use case? Your user is still going to get a json response (and the handlers allow that to be anything).

Also Liked

tfwright

tfwright

Convenience I think would be the main reason. I assume your problem with Plug’s design is that generally it is a bad idea to use errors to control flow. But since we generally want to respond with a user friendly error even when an exception is not expected, this kind of logic seems required here. And once it’s necessary it seems too convenient not to take advantage of in cases where the exception is not strictly speaking unexpected but does not and could not require any special logic other than building the response, because the alternative is needing separate and explicit handling for every single API requirement (like parameter shape/format).

LostKobrakai

LostKobrakai

How did you try that? Because the http request should receive whatever you send as response in the handler. It shouldn’t matter that the error is reraised (e.g. to get properly logged).

See Phoenix.ConnTest — Phoenix v1.7.7 for testing those.

While the latter is a viable option the former is not generally true. Exceptions are the only way to handle errors from LV right now (via Plug.ErrorHandler) and phoenix itself for a long time didn’t have action_fallback while already having means of handling exceptions.

tfwright

tfwright

Are you using Phoenix? My memory was that this works out of the box.

But maybe take a look at Plug.ErrorHandler — Plug v1.20.2

adamu

adamu

My understanding (albeit potentially flawed) is that there are three methods for handling errors, and two places for defining the error response in Phoenix:

  1. Return an :error tuple in the controller and use the fallback controller, as @D4no0 mentioned. Unfortunately, this is not helpful for you, as you’re dealing with a raised Ecto.NoResultsError.
  2. Handle the exception one level up in the router using Plug.ErrorHander, as @tfwright mentioned. However, I believe that this is more designed for handling side effects, as the error is reraised to be handled by point 3 below.
  3. Use the error view. Plug wraps up all exceptions that occur during the request/response, and these are caught by Phoenix in the Endpoint:magic_wand:, which then renders a special error view:magic_wand:. You can customise this to return the JSON response you like - I think this is the best solution. See the documentation.
LostKobrakai

LostKobrakai

Phoenix does a bit more, but conceptionally it works exactly the same as Plug.ErrorHandler. It also reraises errors: phoenix/lib/phoenix/endpoint/render_errors.ex at 246ca7726e14ed94d3d878838cbd6add5a0df3e9 · phoenixframework/phoenix · GitHub

Where Next?

Popular in Questions Top

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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
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
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement