简体   繁体   English

Rails控制器 - 处理404并响应动态HTML错误页面,无论请求格式如何

[英]Rails controller - handle 404 and respond with dynamic HTML error page regardless of request format

Suppose I have the following logic in my ApplicationController: 假设我的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

This renders my custom (and dynamic) 404 error page for all requests in the HTML format. 这将为HTML格式的所有请求呈现我的自定义(和动态)404错误页面。

However, when someone provides a URL indicating a non-HTML format, eg mysite.com/missingfile.png this throws a 500 error becauses I don't have a error_404.png template: 但是,当有人提供指示非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:

How can I override the request format and always show my dynamic HTML 404 page? 如何覆盖请求格式并始终显示我的动态HTML 404页面? I want it to work like twitter: https://twitter.com/missingfile.png . 我希望它像twitter一样工作: https//twitter.com/missingfile.png

A key point is that this is a dynamic 404 page, so the usual public/404.html route does not work for me. 关键点在于这是一个动态的404页面,因此通常的public / 404.html路由对我不起作用。

Thanks! 谢谢!

Do this ... 做这个 ...

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM