Using Rails 4, I can't get rescue_from
to work with ActionController::BadRequest
:
application_controller.rb
rescue_from ActionController::BadRequest, with: :raise_bad_request
def raise_bad_request
render(nothing: true, status: 404)
end
Inside controller you can use rescue_from
only for errors that raise inside your controller (in actions, views or filters).
It looks like ActionController::BadRequest
raises before routing passes request to controller (somewhere in middleware stack).
You can process such errors if you write own middleware like this:
class HandleErrorsMiddleware
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
rescue ActionController::BadRequest
ApplicationController.action(:raise_bad_request).call(env)
end
end
raise_bad_request
should be public method in ApplicationController
You should add this middleware in config/application.rb
config.middleware.insert_before 'ActionDispatch::ParamsParser', 'HandleErrorsMiddleware'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With