Rails 5 way to handle ActionController::ParameterMissing
Asked Answered
M

2

5

If a parameter that's required is missing using strong parameters, the Rails server will respond with an HTTP 500.

This does not give me control over giving the user feedback with what exactly went wrong. Does it not make sense to be able to send them back a message such a required parameter is missing?

What is the "Rails way" of giving appropriate user feedback on ActionController::ParameterMissing? Is one supposed to capture the exception and handle your request response there? It seems wrong to do that in every controller.

Michaels answered 27/9, 2018 at 19:24 Comment(0)
F
9

You can use

rescue_from ActionController::ParameterMissing do |e|
  render 'something'
end

in your ApplicationController (or whatever your parent controller is).

As to whether you should inform users or not, I think it depends on what your controllers are doing. If they are API controllers, it definitely makes sense to handle that gracefully, as the users are responsible for preparing the input. If they are accepting data from your HTML forms it's, in my opinion, not that important as the missing parameters probably mean that the user tinkered with the HTML, or something went really wrong inside the browser.

Fenestration answered 27/9, 2018 at 19:29 Comment(0)
H
5

Since you mention wanting to communicate the error specifics back to the user, you could do something like the following:

# app/controllers/application_controller.rb

rescue_from ActionController::ParameterMissing do |exception|
  render json: { error: exception.message }, status: :bad_request
end

You can also define a method to handle a specific exception, if you'd prefer to break up the handling logic:

# app/controllers/application_controller.rb

rescue_from ActionController::ParameterMissing, with: :handle_parameter_missing

def handle_parameter_missing(exception)
  render json: { error: exception.message }, status: :bad_request
end

Both of the above examples will return a JSON response like so: {"error"=>"param is missing or the value is empty: [field_name]"}

For an API-only application, I think this is valuable information to pass on.

More info:

Hoarding answered 16/11, 2020 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.