Jan Krupa
Jan Krupa

Reputation: 506

Rescue from ActionController::UnpermittedParameters

I'm trying to handle ActionController::UnpermittedParameters.

I've defined a block in ApplicationController

  rescue_from ActionController::UnpermittedParameters do |error|
    message = "Invalid parameter: %s. " % error.params.to_sentence
    message << 'Please verify that the parameter name is valid and the values are the correct type.'
    format.html { redirect_to :back, alert: 'You passed wrong params! ' + message }
  end

But, when I execute code, which should be handled, the rescue block is not executed.

enter image description here

What am I doing wrong?

Upvotes: 2

Views: 494

Answers (2)

Jan Krupa
Jan Krupa

Reputation: 506

I don't know what was wrong about my question, but I write my own ErrorHandler module, which works fine now.

# Error module to Handle errors globally
# include Error::ErrorHandler in application_controller.rb
module Error
  module ErrorHandler
    def self.included(klass)
      klass.class_eval do
        rescue_from ActionController::UnpermittedParameters, with: :unpermitted_parameter
      end
    end

    private
    def unpermitted_parameter(error)
      message = "You have entered an unpermitted parameter: %s. " % error.params.to_sentence
      message << 'Please verify that the parameter name is valid and the values are the correct type.'
      Rails.logger.info(Rainbow(" !!! UNPERMITTED: !!! #{error.to_s}").fg(:red))

      respond_to do |format|
        format.html { redirect_back fallback_location: { action: "index" }, 
                      :alert => message }
        format.js
      end
    end
  end
end

Upvotes: 0

Alex Suslyakov
Alex Suslyakov

Reputation: 2222

I guess your request is not of HTML format, so format.html { } block will not be executed.

Try to leave only redirect_to :back, alert: 'You passed wrong params! ' + message part

Upvotes: 1

Related Questions