rst*_*rim 22 error-handling routing ruby-on-rails
我需要在rails应用程序中实现一个自定义错误页面,允许我使用erb.
我一直在关注这个教程(http://blog.tommilewski.net/2009/05/custom-error-pages-in-rails/),我无法让它在本地(或远程)工作.我正在运行Rails 2.3.5
这是方法的要点.
1)在'application_controller'中,我过度使用"render_optional_error_file(status_code)"方法,并将可见性设置为"protected",就像这样.
protected
def render_optional_error_file(status_code)
known_codes = ["404", "422", "500"]
status = interpret_status(status_code)
if known_codes.include?(status_code)
render :template => "/errors/#{status[0,3]}.html.erb", :status => status, :layout => 'errors.html.erb'
else
render :template => "/errors/unknown.html.erb", :status => status, :layout => 'errors.html.erb'
end
end
def local_request?
true
end
Run Code Online (Sandbox Code Playgroud)
我还创建了被称为视图中的文件夹errors,并创建了以下观点:404.html.erb,422.html.erb,500.html.erb,unknown.html.erb和我创建了一个新的布局"errors.html.erb"
我似乎无法让它发挥作用.我一直试图通过导航到触发404页面http://localhost:3000/foobar- 但是404.html.erb,我似乎没有得到新的标准apache 500错误.发生这种情况时,我都试一下mongrel_rails start和mongrel_rails start -e production.
gal*_*key 32
我建议使用异常来呈现这样的错误页面,这样你就可以使用继承来对错误消息进行分组......
首先,声明一些(我通常在application_controller.rb中做)
class Error404 < StandardError; end
class PostNotFound < Error404; end
Run Code Online (Sandbox Code Playgroud)
然后将代码添加到ApplicationController来处理它们
class ApplicationController < ActionController::Base
# ActionController::RoutingError works in Rails 2.x only.
# rescue_from ActionController::RoutingError, :with => :render_404
rescue_from Error404, :with => :render_404
rescue_from PostNotFound, :with => :render_post_not_found
def render_404
respond_to do |type|
type.html { render :template => "errors/error_404", :status => 404, :layout => 'error' }
type.all { render :nothing => true, :status => 404 }
end
true
end
def render_post_not_found
respond_to do |type|
type.html { render :template => "errors/shop_not_found", :status => 404, :layout => 'error' }
type.all { render :nothing => true, :status => 404 }
end
true
end
end
Run Code Online (Sandbox Code Playgroud)
这会使错误布局呈现错误/ error_404.应该让你开始:)
在你的target_controller中:
raise PostNotFound unless @post
Run Code Online (Sandbox Code Playgroud)
编辑
有关ActionController :: RoutingError不适用于rails 3的原因的更长解释: Rails 3.0异常处理.
"如果您的应用程序依赖于使用自己的路径扩展您的应用程序的引擎,那么事情就会破裂,因为这些路线永远不会被解雇!"