gmc
How to handle actions with not matching parameters
I’ve created a JSON API and deconstruct parameters in the controller action like this:
def create(conn, %{“item” => item_params}) do
…
end
Now I’d like to capture the cases where the pattern isn’t matched (e.g. not having the “item” in the request JSON) and send an appropriate error JSON.
How can this be done? Now I just get “no function clause matching in …create/2” error. After some research I found the following issue which would suit my needs, but it was closed by José:
https://github.com/phoenixframework/phoenix/issues/2386
Marked As Solved
Nicd
Write a second clause for the function:
def create(conn, params)
def create(conn, %{“item” => item_params}) do
do_stuff()
end
def create(conn, _params) do
send_error()
end
Also Liked
stefanchrobot
The pattern matching is applied top to bottom:
# This is optional.
def create(conn, params)
# Attempted first, matches on correct params.
def create(conn, %{“item” => item_params}) do
do_stuff()
end
# Matches everything else.
def create(conn, _params) do
send_error()
end
stefanchrobot
How about https://elixir-lang.org/getting-started/pattern-matching.html
EDIT: oh, I see. There’s no mention of pattern matching in function heads.
Sebb
I just wanted to point to the documentation about pattern matching in functions, but there seems to be none. Neither in elixir-hexdocs nor in the guide…? Am I missing something?
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









