【问题标题】:How to use rescue_from with Rails 6?如何在 Rails 6 中使用rescue_from?
【发布时间】:2020-04-19 03:11:44
【问题描述】:

显然rescue_from 应该捕获异常,但这并没有按预期工作:

class ApplicationController < ActionController::Base
  rescue_from ActionController::RoutingError, with: :not_found

  def not_found
    text: 'Not found'
  end
end

规格:

specify 'Not found' do
  visit '/zzz'
  expect(page.status_code).to eq 200
end
Failure/Error: visit '/zzz'

     ActionController::RoutingError:
       No route matches [GET] "/zzz"

在开发环境中的行为相同。

但是,修复其他错误(例如 RuntimeError)确实可以按预期工作。

文档:https://apidock.com/rails/v6.0.0/ActiveSupport/Rescuable/ClassMethods/rescue_from

Rails 6.0.2

为什么RoutingError 不能与rescue_from 一起使用?在调用控制器之前,RoutingError 是在中间件中引发还是由路由器引发?有没有其他方法可以捕获RoutingError

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    在到达控制器之前会引发路由器错误,您可以在 routes.rb 文件末尾使用通配符路由来匹配与其他路由不匹配的任何内容,并将该点路由到特定控制器操作。

    类似:

    match '*foo', to: 'application#not_found'
    

    (没试过,你可能需要稍微调整一下,但我认为这个想法很清楚)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 2013-10-12
      • 2016-03-04
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多