本文介绍了在 Rails 4 中救援来自 ActionController::RoutingError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下错误:
ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")
我想为不存在的链接显示 error404 页面.
I want to show error404 page for links that are not existing.
我怎样才能做到这一点?
How can I achieve that?
推荐答案
在application_controller.rb
中添加以下内容:
# You want to get exceptions in development, but not in production.
unless Rails.application.config.consider_all_requests_local
rescue_from ActionController::RoutingError, with: -> { render_404 }
end
def render_404
respond_to do |format|
format.html { render template: 'errors/not_found', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
我通常也会挽救以下异常,但这取决于你:
I usually also rescue following exceptions, but that's up to you:
rescue_from ActionController::UnknownController, with: -> { render_404 }
rescue_from ActiveRecord::RecordNotFound, with: -> { render_404 }
创建错误控制器:
class ErrorsController < ApplicationController
def error_404
render 'errors/not_found'
end
end
然后在routes.rb
unless Rails.application.config.consider_all_requests_local
# having created corresponding controller and action
get '*path', to: 'errors#error_404', via: :all
end
最后一件事是在 /views/errors/
下创建 not_found.html.haml
(或您使用的任何模板引擎):
And the last thing is to create not_found.html.haml
(or whatever template engine you use) under /views/errors/
:
%span 404
%br
Page Not Found
这篇关于在 Rails 4 中救援来自 ActionController::RoutingError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!