How to rescue page not found 404 in rails?

对着背影说爱祢 提交于 2019-12-30 16:36:13

问题


How to rescue page not found if user add wrong url in rails. I hope to show 404 page present in public folder if the url is invalid. How to do that? I was browsing about it but could not find a solution. I tried many ways to fix the problem, but they don't seem to be working. I am stuck here, please help.


回答1:


Solution for Rails 4

On routes.rb:

get '*unmatched_route', to: 'application#not_found'

On application_controller.rb:

def not_found
  # Your exception handling code here
end



回答2:


i found the solution, check this out => http://techoctave.com/c7/posts/36-rails-3-0-rescue-from-routing-error-solution (great solution)

routes.rb :

# at the end of you routes.rb
match '*a', :to => 'errors#routing', via: :get

errors_controller.rb :

class ErrorsController < ApplicationController
  def routing
    render_404
  end
end

application.rb :

rescue_from ActionController::RoutingError, :with => :render_404

 private
  def render_404(exception = nil)
    if exception
        logger.info "Rendering 404: #{exception.message}"
    end

    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end


来源:https://stackoverflow.com/questions/21654826/how-to-rescue-page-not-found-404-in-rails

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