Yesterday my application was visited by yandex bot with an invalid URL
/restday?biG%D9%02
and for this application is throwing an error
ArgumentError: invalid byte sequence in UTF-8
I need to render 400.html static page with status 400 instead of 404 whenever there is a invalid character error. I followed the solutions from this question and rack-robustness gem but it doesn't serve the purpose as it shows 404 or redirects to particular page.
I have added the following to /config/application.rb
require "#{Rails.root}/lib/handle_invalid_percent_encoding.rb"
config.middleware.insert 0, HandleInvalidPercentEncoding
And this is my middleware handle_invalid_percent_encoding.rb
require 'rack'
class HandleInvalidPercentEncoding
def initialize(app) @app = app end def call(env) request = Rack::Request.new(env.dup) temp = request.params rescue :bad_form_data if temp == :bad_form_data error_response else @app.call(env) end end private def error_response # serve static html file end
end
P.S I need to render bad request error only when the argument error is Invalid encoding.