Rescue Phoenix.MissingParamError and return json

In my controller action i have two scrub_params clauses:

  plug :scrub_params, "account"
  plug :scrub_params, "studio"

When one of params is not present Phoenix raises Phoenix.MissingParamError. Is there any way to rescue this error and return some json message for user?

plug MyApp.ScrubParams, "account"

defmodule MyApp.ScrubParams do
  def init(key), do: key
  def call(conn, key) do
    Phoenix.Controller.scrub_params(conn, key)
  rescue
    Phoenix.MissingParamError ->
      conn
      |> Plug.Conn.put_status(:bad_request)
      |> Phoenix.Controller.render(MyApp.ErrorView, "bad_params.json", key: key)
      |> Plug.Conn.halt()
  end
end
2 Likes

Shouldn’t there be a try somewhere? I’ve never seen rescue for def.

Heh, here it is https://hexdocs.pm/elixir/Kernel.html#def/2-rescue-catch-after.

1 Like

Function bodies support rescue, catch and after as SpecialForms.try/1 does

:slight_smile:

3 Likes

whaaaaaaaaaaaaaaaaaaaaaat

I can’t believe I’ve missed this!

1 Like