简体   繁体   English

ruby on rails 3.1全局异常处理程序

[英]ruby on rails 3.1 global exception handler

I'm developing an app with Rails 3.1.2 but I can't find some documentation that works with errors / exception (like 404) on this version of rails. 我正在使用Rails 3.1.2开发应用程序,但是在此版本的Rails上找不到能解决错误/异常(例如404)的文档。

i have tried things like: 我尝试过类似的事情:

In application controller 在应用程序控制器中

rescue_from ActiveRecord::RecordNotFound,ActionController::RoutingError, 
             ActionController::UnknownController, ActionController::UnknownAction, :NoMethodError, :with => :handle_exception 

  def handle_exception 
   render :template => 'error_pages/error'
  end 

environment/development.rb

config.consider_all_requests_local = false

Where can I find a solution? 在哪里可以找到解决方案?

Thanks in advance... 提前致谢...

This should work: 这应该工作:

In application controller 在应用程序控制器中

  class NotFound < StandardError; end
  rescue_from NotFound, :with => :handle_exception

  def handle_exception 
   render :template => 'error_pages/error'
  end

Look at action_dispatch/middleware/show_exceptions . 查看action_dispatch / middleware / show_exceptions

From the documentation in the source: 从源代码中的文档中:

# This middleware rescues any exception returned by the application
# and wraps them in a format for the end user.

Short story short, it renders ActionDispatch::ShowExceptions.render_exception when the wrapped application (Rails, in your case), encounters an unrescued exception. 简而言之,当包装的应用程序(在您的情况下为Rails)遇到无法挽救的异常时,它将呈现ActionDispatch::ShowExceptions.render_exception

If you look through the default implementation, it ends up rendering something like public/500.html , which is what you see in the production environment. 如果您查看默认的实现,最终public/500.html类似于public/500.html ,这是您在生产环境中看到的。 Overwrite the method or method chain it as you see fit to add your own implementation. 覆盖您认为合适的方法或方法链,以添加自己的实现。

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

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