简体   繁体   English

rescue_from不使用ActionController :: BadRequest

[英]rescue_from not working with ActionController::BadRequest

Using Rails 4, I can't get rescue_from to work with ActionController::BadRequest : 使用Rails 4,我无法使rescue_fromActionController::BadRequest

application_controller.rb 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). 在控制器内部,您只能将rescue_from用于控制器内部引发的错误(在操作,视图或过滤器中)。

It looks like ActionController::BadRequest raises before routing passes request to controller (somewhere in middleware stack). 看起来像ActionController::BadRequest在路由将请求传递给控制器​​(中间件堆栈中的某个地方)之前引发。

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 raise_bad_request应该是ApplicationController公共方法

You should add this middleware in config/application.rb 您应该在config/application.rb添加此中间件

config.middleware.insert_before 'ActionDispatch::ParamsParser', 'HandleErrorsMiddleware' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM