我们有一个使用本教程设置自定义 404 和 500 页的 Rails 服务器:
http://ramblinglabs.com/blog/2012/01/rails-3-1-adding-custom-404-and-500-error-pages
虽然它工作得很好,并且为各种路径抛出 404,但它在尝试访问任何类型的后缀路径(如 en/foo.png、en/foo.pdf、en/foo.xml,...)时会生成内部服务器错误 500
但是像 en/file.foo 这样的东西会抛出 404。所以只有有效的后缀会抛出 500。
路线结束.rb:
if Rails.application.config.consider_all_requests_local
match '*not_found', to: 'errors#error_404'
end
application_controller.rb
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :render_500
rescue_from ActionController::RoutingError, with: :render_404
rescue_from ActionController::UnknownController, with: :render_404
rescue_from ::AbstractController::ActionNotFound, with: :render_404
rescue_from ActiveRecord::RecordNotFound, with: :render_404
end
protected
def render_404(exception)
@not_found_path = exception.message
respond_to do |format|
format.html { render template: 'errors/error_404', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def render_500(exception)
logger.fatal(exception)
respond_to do |format|
format.html { render template: 'errors/error_500', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
500 出现:
Missing template errors/error_404 with {:locale=>[:de, :en], :formats=>[:png], :handlers=>[:erb, :builder, :coffee, :arb, :haml]}