Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rescue_from not working with ActionController::BadRequest

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
like image 339
Tom Rossi Avatar asked Apr 21 '14 14:04

Tom Rossi


1 Answers

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' 
like image 161
mikdiet Avatar answered Nov 09 '22 08:11

mikdiet