Handle phoenix action with no matching clause

Assume a router is configured to call an action that does pattern matching on the body of the request:

def post_foobar(conn, %{ "foo" => foo, "bar" => bar }) do
   ....
end 

When a request is done on the right root, but with a body that does not match (for example, there is no “foo” in the body), no clause of the post_foobar function is found, and it results in a 400 with an “Internal server error” message.

A simple way to handle that is to add matching clause to do a cleaner response:

def post_foobar(conn, %{ "foo" => foo, "bar" => bar }) do
   ....
end 

def post_foobar(conn, _) do
   conn |> send_resp(400, ....) 
end

Is there a way to factor it at the Controller level, so that all actions in a controller behave in a custom way when pattern matching fail ?

2 Likes

Phoenix allows you to override action/2 in controllers, which does handle calling the action functions. You might be able to build something to generate a custom action/2 function in all your controllers, which does respond to match errors in a common way.

3 Likes