1

我正在运行 Rails 3.0.8,Webrick 网络服务器在生产模式下使用这样的命令启动

RAILS_ENV=production rails server

我有以下问题。

我读过,生产模式下的 rails 应该处理所有异常和错误。但是当我试图在生产模式下获取不存在的项目时,我实际上仍然收到错误消息“ActiveRecord::RecordNotFound”。

我也读过

rescue_from ActiveRecord::RecordNotFound, :with => :page_not_found

这样的黑客,但我认为这不是 Rails 方式。

这是我的 production.rb 文件内容:

BeerPub::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # The production environment is meant for finished, "live" apps.
  # Code is not reloaded between requests
  config.cache_classes = true
  config.whiny_nils = false

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_view.debug_rjs             = false
  config.action_controller.perform_caching = true

  # Specifies the header that your server uses for sending files
  config.action_dispatch.x_sendfile_header = "X-Sendfile"

  # For nginx:
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

  # If you have no front-end server that supports something like X-Sendfile,
  # just comment this out and Rails will serve the files

  # See everything in the log (default is :info)
  # config.log_level = :debug

  # Use a different logger for distributed setups
  # config.logger = SyslogLogger.new

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Disable Rails's static asset server
  # In production, Apache or nginx will already do this
  config.serve_static_assets = true

  # Enable serving of images, stylesheets, and javascripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify
end

如您所见,这很常见。

请帮我解决这个问题。

升级版:

我也可以得到以下错误

Routing Error

No route matches "/lol"

这是另一种类型的例外,但问题是一样的。处理这种情况的最佳方法是什么?

4

1 回答 1

0

“我读过,生产模式下的 Rails 应该处理所有异常和错误。”

这是不正确的,Rails 本身不会捕获异常,但只是在生产模式下你有不同的方法来处理它们。

你写的rescue_from方法是绝对正确的。

许多 Rails 开发人员并不关心挽救 RecordNotFound 异常,因为一个简单的事实是,根据应用程序,是用户做错了什么。

然而,有些应用程序喜欢捕获此异常并执行自定义操作,例如重定向、呈现文本或不同的视图。

于 2011-07-18T14:57:11.240 回答