Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 way to handle ActionController::ParameterMissing

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.

like image 849
randombits Avatar asked Jan 02 '23 19:01

randombits


2 Answers

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.

like image 150
Marcin Kołodziej Avatar answered Jan 05 '23 16:01

Marcin Kołodziej


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:

  • Rails API rescue_from documentation
  • Handling Errors in an API Application the Rails Way
like image 23
Dave Powers Avatar answered Jan 05 '23 16:01

Dave Powers