1
votes

I wrote a plug which I want to use in two or more controllers.

For first controller there are two variables in params %{params: %{“param1” => param01, “param2” => param02}} = conn and for second controller there is just one variable %{params: %{“param1” => param01} = conn.

I used %{params: %{“param1” => param01, “param2” => param02}} = conn for pattern matching in the plug. And it throws (MatchError) no match of right hand side value: when a request comes to second controller.

I want a pattern match which will handle both cases gracefully. Is there a way to set param02 to nil for second controller instead of getting an error.

Thanks in advance for your answer. I just started learning Elixir/Phoenix Framework and still new to it.

1

1 Answers

3
votes

You cannot do this with pattern matching. You can instead extract params and assign param2 within your code:

def foo(%{params: %{“param1” => param01} = params} = conn) do
  param02 = params["param2"]
  ...
end

param02 will now be set to the conn.params["param2"] if it's present, and nil otherwise.