Rails:特定 HTTP 错误代码的自定义行为

2024-04-18

我正在开发一个 RoR 网站,希望单独处理服务器错误(400、404、500 等)。另外,由于网站是动态的,我想在 Rails 环境中处理错误,而不是在服务器级别。 我想做的一个例子是,当用户遇到无法加载或根本不存在的页面或模板时,向用户提供可选材料或搜索​​栏。

因此,我做了一些阅读,我认为使用rescue_from异常处理程序是我的情况的最佳选择。 (如果你们有不同的意见,我会非常高兴)。

我有一个简单的工作原型(请参阅下面的代码)并正在运行,但是,当我在代码中包含以下异常处理程序时,我收到错误:

rescue_from ActionController::MissingTemplate,          :with => :not_found #404

现在,我看不到我有拼写错误,并且我在网络上发布的代码中看到了这一行。但是,当我包含它时,我收到以下路由错误:

Routing Error No route matches "/errorhandle" with {:method=>:get}

我正在开发 Rails 2.3.5,也许这与它有关?

class ApplicationController < ActionController::Base

    helper :all # include all helpers, all the time

    protect_from_forgery #See ActionController::RequestForgeryProtection for details

    #ActiveRecord exceptions
    rescue_from ActiveRecord::RecordNotFound, :with => :not_found #400   

    #ActiveResource exceptions  
    rescue_from ActiveResource::ResourceNotFound, :with => :not_found #404

    #ActionView exceptions
    rescue_from ActionView::TemplateError, :with => :not_found #500

    #ActionController exceptions
    rescue_from ActionController::RoutingError, :with => :not_found #404   

    rescue_from ActionController::UnknownController, :with => :not_found #404 

    rescue_from ActionController::MethodNotAllowed, :with => :not_found #405   

    rescue_from ActionController::InvalidAuthenticityToken, :with => :not_found #405

    rescue_from ActionController::UnknownAction, :with => :not_found #501

    # This particular exception causes all the rest to fail.... why?
    # rescue_from ActionController::MissingTemplate, :with => :not_found #404
    
    protected
    def not_found
        render :text => "Error", :status => 404
    end

    # Scrub sensitive parameters from your log
    # filter_parameter_logging :password 
end

快速浏览一下这些:http://www.ruby-forum.com/topic/47898 http://www.ruby-forum.com/topic/47898

http://henrik.nyh.se/2008/09/404-invalid-rails-format http://henrik.nyh.se/2008/09/404-invalid-rails-format

特别是第一个链接中的帖子:

您不能使用常规的“rescue”关键字来拯救 MissingTemplate 例外。

请改用rescue_action,例如:

def rescue_action(exception)
  if ::ActionController::MissingTemplate === exception
     render :text => 'rescued'
  else
     super
  end
end

Kent.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails:特定 HTTP 错误代码的自定义行为 的相关文章

随机推荐