ruby-on-rails - Rails Controller - 处理 404 并以动态 HTML 错误页面响应,无论请求格式如何

标签 ruby-on-rails ruby-on-rails-3 error-handling http-status-code-404

假设我的 ApplicationController 中有以下逻辑:

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

def handle_routing_error(exception)
 logger.info { "handling routing error: #{exception.message}" }
 render template: 'errors/error_404', status: 404
end

这会以 HTML 格式为所有请求呈现我的自定义(和动态)404 错误页面。

但是,当有人提供了一个指示非 HTML 格式的 URL 时,例如mysite.com/missingfile.png 这会引发 500 错误,因为我没有 error_404.png 模板:

Missing template errors/error_404, public_site/error_404, application/error_404 with {:locale=>[:en], :formats=>[:png], :handlers=>[:erb, :builder, :coffee, :rabl, :haml]}. Searched in:

如何覆盖请求格式并始终显示我的动态 HTML 404 页面?我希望它像推特一样工作:https://twitter.com/missingfile.png .

关键是这是一个动态 404 页面,所以通常的 public/404.html 路由对我不起作用。

谢谢!

最佳答案

这样做...

#config/routes
get "*unmatched_route", :to => "application#error_page"


#controllers/application_controller
def error_page
  render :template => 'errors/error_404', status: 404
end

关于ruby-on-rails - Rails Controller - 处理 404 并以动态 HTML 错误页面响应,无论请求格式如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14950934/

相关文章:

javascript - Rails 6 webpack 抛出 'Uncaught ReferenceError: $ is not defined'

ruby-on-rails - 使用事件模型序列化程序为充当可标记标签的标签加载 JSON 时出错

javascript - 如何在 Rails 3 应用程序中插入 CKEditor 插件?

php - laravel未定义偏移量0

ruby-on-rails - Factorygirl 通过模特有一个关联

mysql - Vanity 不适用于 MySql

ruby-on-rails - Rails has_many :through Uninitialized constant

ruby-on-rails - 工具提示截断

error-handling - 程序崩溃时如何处理MPI错误

python - 在 QMessageBox 中显示 MySQL 错误