fireproofsocks
Examples of best practices for handling bad requests in Phoenix?
I’m wondering if anyone has any educational (i.e. simplified) examples that demonstrate best practices when it comes to handling bad requests in a Phoenix application. For educational purposes, let’s consider just one case:
Creating a record: how to handle a bad payload
Maybe your router has something like this:
scope "/api", MyAppWeb do
resources("/things", ThingController)
end
And maybe your controller has something like this:
def create(conn, %{"data" => data}) do
with {:ok, thing} <- ThingCreate.create(data) do
conn
|> put_status(:created)
|> render("thing.json", thing: thing)
end
end
You’ll notice that the route won’t pattern-match if your payload is something like [] (an empty JSON array)…
It’s tempting to write another controller function that would handle the bad data:
def create(conn, _bad_data) do
# return an error...
but that’s just smelly
This article looked promising, but it didn’t get into details: https://medium.com/appunite-edu-collection/handling-failures-in-elixir-and-phoenix-12b70c51314b
I think that the correct response for this situation would be a 400 (e.g. 422), but not simply a 404. What is the cleanest way to return an error message with specifics and a proper status code? Is this best handled in the fallback controller? Does anyone have a complete example of this?
Thanks for sharing!
First Post!
dimitarvp
I don’t see that, you don’t have any additional assertions in the function’s head save for the map requirement with a singular "data" key – nor do you have when clauses. Why wouldn’t this:
def create(conn, %{"data" => data}) do
…match %{"data" => []}? Or you meant if the object itself is not a map at all and just []?
Assuming it’s the latter, then:
…is not a factual statement. In our team we use pattern-matching function heads all the time and they really do help readability and expressing your intent much better than huge case or cond arms in the code of a single controller action function.
Last Post!
dimitarvp
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









