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

What you want to use is case.

case attrs do
  %{"file" => file} -> # do something with file
  _ -> # do something else
end
4 Likes

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.

2 Likes

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.

2 Likes

Thank you, all of you, for the help!

1 Like

Glad we could help.

Consider marking one of the answers as the solution. It helps the future readers.

2 Likes