abraun
How to recover from (MatchError) no match of right hand side value: %{}
What is the best solution if I want to try to pattern match and do something else if no match was found?
Let’s say, I want to pattern match the file like this:
%{"file" => file} = attrs
Maybe the file field exists, maybe it doesn’t.
Is there a way to try() pattern match, else if no match do something else?
Thank you for your help!
Best,
Andreas
Marked As Solved
NobbZ
What you want to use is case.
case attrs do
%{"file" => file} -> # do something with file
_ -> # do something else
end
Also Liked
Ankhers
You could also have multiple function heads for this.
defmodule Foo do
def bar(%{"file" => file}) do
# Do something if the "file" key is found
end
def bar(attrs) do
# Do something if none of the previous function heads match
end
end
Keep in mind you can have more than two function heads.
dimitarvp
Previous two replies are what I would usually reach for.
That being said, you can also do this:
map1 = %{file: "what.ever"}
map2 = %{name: "myself", age: 177}
match? %{file: _}, map1 # this yields true
match? %{file: _}, map2, # this yields false
However, this would mean you will use if / else in your code which is something I actively avoid ever since I learned functional programming. Using case is a very slight (if any) improvement over it but nowadays I’d go for @Ankhers’s approach, every time.
dimitarvp
Glad we could help.
Consider marking one of the answers as the solution. It helps the future readers.
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









