Dynamic error pages in Rails 3

巧了我就是萌 提交于 2019-11-27 10:52:14

In rails 3.2, it's easier than that:

Add this to config/application.rb:

config.exceptions_app = self.routes

That causes errors to be routed via the router. Then you just add to config/routes.rb:

match "/404", :to => "errors#not_found"

I got this info from item #3 on the blog post "My five favorite hidden features in Rails 3.2" by By José Valim.

I would suggest using rescue_from instead. You would just rescue from specific errors rather than overriding rescue_action_in_public. This is especially useful when dealing with user-defined errors or controller-specific errors.

# ApplicationController
rescue_from ActionController::RoutingError, :with => :render_404
rescue_from ActionController::UnknownAction, :with => :render_404
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
rescue_from MyApp::CustomError, :with => :custom_error_resolution

def render_404
  if /(jpe?g|png|gif)/i === request.path
    render :text => "404 Not Found", :status => 404
  else
    render :template => "shared/404", :layout => 'application', :status => 404
  end
end

# UsersController
rescue_from MyApp::SomeReallySpecificUserError, :with => :user_controller_resolution

http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html

The exception notifier has a method called notify_about_exception to initiate the error notification on demand.

class ApplicationController < ActionController::Base
  include ExceptionNotification::Notifiable

  rescue_from Exception, :with => :render_all_errors

  def render_all_errors(e)
    log_error(e) # log the error
    notify_about_exception(e) # send the error notification

    # now handle the page
    if e.is_a?(ActionController::RoutingError)
      render_404(e)
    else
      render_other_error(e)
    end
  end

  def render_404_error(e)
   # your code
  end

  def render_other_error(e)
   # your code
  end
end

I have also faced such problem. The problem is because of attachment_fu gem or plugin. Just uninstall it and use any other plugin or gem will solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!