ken*_*enn 11 templates ruby-on-rails exception
从Rails 3.0开始,我不时收到这样的异常通知:
ActionView::MissingTemplate: Missing template [...] with {:locale=>[:en],
:formats=>[:text], :handlers=>[:erb, :builder, :haml]}. Searched in: * [...]
Run Code Online (Sandbox Code Playgroud)
例如,像http://example.com/some/path/robots.txt这样的任意手写URL 会引发错误.不好玩.
很久以前我在这张票中报告了这个问题,并且一直在使用这里提到的补丁,但问题仍然存在.
此博客文章中建议修复,
http://trevorturk.wordpress.com/2011/12/09/handling-actionviewmissingtemplate-exceptions/
要使用它:
respond_to do |format|
format.js
end
Run Code Online (Sandbox Code Playgroud)
但它对我来说并不合适,因为我对使用多种格式重载动作不感兴趣.在我的应用程序中,HTML和JSON API有单独的URL,所以简单render
就足够了.
我应该吞下异常rescue_from ActionView::MissingTemplate
并自己返回406吗?
有没有更好的方法来处理这种情况?
或者我可以这样问 - 首先,在生产中提出这种例外是否有任何实际用处?
小智 6
如果您不需要格式化路由,可以在路由规范中使用:format => false禁用它们,例如
get '/products' => 'products#index', :format => false
Run Code Online (Sandbox Code Playgroud)
这将生成一个RoutingError,它将转换为404 Not Found.或者,您可以将其限制为多种预定义格式:
get '/products' => 'products#index', :format => /(?:|html|json)/
Run Code Online (Sandbox Code Playgroud)
如果您想要一个格式化的网址但希望它限制为单一格式,那么您可以这样做:
get '/products.json' => 'products#index', :format => false, :defaults => { :format => 'json' }
Run Code Online (Sandbox Code Playgroud)
有许多有效的理由在生产中引发此错误 - 例如,部署中丢失的文件,或者您可能希望通知有人试图破解您的应用程序的URL.
归档时间: |
|
查看次数: |
4253 次 |
最近记录: |