Rescue_from does not work with ActionController :: BadRequest

Using Rails 4, I cannot 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 
+6
source share
1 answer

Inside the controller, you can use rescue_from only for errors that occur inside your controller (in actions, views or filters).

It seems that ActionController::BadRequest rises before the routing passes the request to the controller (somewhere on the middleware stack).

You can handle such errors if you write your own middleware as follows:

 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 must be a public method in ApplicationController

You must add this middleware to config/application.rb

 config.middleware.insert_before 'ActionDispatch::ParamsParser', 'HandleErrorsMiddleware' 
+7
source

All Articles