我想在Rails中“伪造”一个404页面。在PHP中,我只会发送一个带有错误代码的报头:
header("HTTP/1.0 404 Not Found");
Rails如何做到这一点?
我想在Rails中“伪造”一个404页面。在PHP中,我只会发送一个带有错误代码的报头:
header("HTTP/1.0 404 Not Found");
Rails如何做到这一点?
当前回答
为了测试错误处理,你可以这样做:
feature ErrorHandling do
before do
Rails.application.config.consider_all_requests_local = false
Rails.application.config.action_dispatch.show_exceptions = true
end
scenario 'renders not_found template' do
visit '/blah'
expect(page).to have_content "The page you were looking for doesn't exist."
end
end
其他回答
routes.rb
get '*unmatched_route', to: 'main#not_found'
main_controller.rb
def not_found
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
你也可以使用渲染文件:
render file: "#{Rails.root}/public/404.html", layout: false, status: 404
你可以选择是否使用该布局。
另一种选择是使用Exceptions来控制它:
raise ActiveRecord::RecordNotFound, "Record not found."
我想对任何不是管理员的登录用户抛出一个“正常的”404,所以我最终在Rails 5中写了这样的东西:
class AdminController < ApplicationController
before_action :blackhole_admin
private
def blackhole_admin
return if current_user.admin?
raise ActionController::RoutingError, 'Not Found'
rescue ActionController::RoutingError
render file: "#{Rails.root}/public/404", layout: false, status: :not_found
end
end
这些会帮助你……
应用程序控制器
class ApplicationController < ActionController::Base
protect_from_forgery
unless Rails.application.config.consider_all_requests_local
rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: lambda { |exception| render_error 404, exception }
end
private
def render_error(status, exception)
Rails.logger.error status.to_s + " " + exception.message.to_s
Rails.logger.error exception.backtrace.join("\n")
respond_to do |format|
format.html { render template: "errors/error_#{status}",status: status }
format.all { render nothing: true, status: status }
end
end
end
错误的控制器
class ErrorsController < ApplicationController
def error_404
@not_found_path = params[:not_found]
end
end
视图/错误/error_404.html.haml
.site
.services-page
.error-template
%h1
Oops!
%h2
404 Not Found
.error-details
Sorry, an error has occured, Requested page not found!
You tried to access '#{@not_found_path}', which is not a valid page.
.error-actions
%a.button_simple_orange.btn.btn-primary.btn-lg{href: root_path}
%span.glyphicon.glyphicon-home
Take Me Home
所选的答案在Rails 3.1+中不工作,因为错误处理程序被移动到中间件(见github问题)。
这是我找到的解决方案,我很满意。
控制器:
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :handle_exception
end
def not_found
raise ActionController::RoutingError.new('Not Found')
end
def handle_exception(exception=nil)
if exception
logger = Logger.new(STDOUT)
logger.debug "Exception Message: #{exception.message} \n"
logger.debug "Exception Class: #{exception.class} \n"
logger.debug "Exception Backtrace: \n"
logger.debug exception.backtrace.join("\n")
if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
return render_404
else
return render_500
end
end
end
def render_404
respond_to do |format|
format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def render_500
respond_to do |format|
format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
在application.rb:
config.after_initialize do |app|
app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end
在我的资源(显示,编辑,更新,删除):
@resource = Resource.find(params[:id]) or not_found
这当然可以改进,但至少,我对not_found和internal_error有不同的视图,而不重写核心Rails函数。