简体   繁体   English

对于缺少的资产,Rails忽略ActionView :: Template :: Error

[英]Rails ignore ActionView::Template::Error for missing assets

ActionView::Template::Error (leagues/lal11.png isn't precompiled):

Errors of this sort happen in my app when a new league is added but the corresponding image hasn't been precompiled. 这种错误发生在我的应用程序中,当添加新联盟但相应的图像尚未预编译时。

I understand why this is happening; 我明白为什么会这样; the asset manifest is missing the relevant path and so rails can't determine the digest for it. 资产清单缺少相关路径,因此rails无法确定其摘要。 However, killing the whole app because of a simple missing image is stupid. 然而,由于简单的丢失图像而杀死整个应用程序是愚蠢的。 Is there a way to catch this specific exception? 有没有办法捕获这个特定的例外?

Blaming the asset pipeline in this case seems wrong. 在这种情况下责备资产管道似乎是错误的。 Its an optional thing that is there to speed up your application. 它是一个可选的东西,可以加快您的应用程序。 If you're happy with a slower application that will fallback, this is easily configurable in config/environments/production.rb 如果您对可以回退的较慢应用程序感到满意,可以在config / environments / production.rb中轻松配置

 # Don't fallback to assets pipeline if a precompiled asset is missed
 config.assets.compile = false

I wouldn't recommend doing this though! 我不建议这样做!

Although one could argue that this isn't a case where an exception error should be raised... the fact is you're pulling an image that doesn't exist. 虽然有人可能会争辩说这不是应该引发异常错误的情况......事实上你是在拉一个不存在的图像。

So there is an error that your code needs to handle. 因此,您的代码需要处理错误。 IMO its better in Object Oriented code to fail massively instead of cleverly. IMO在面向对象的代码中更好地大规模而不是巧妙地失败。 This fail creates a nice failure message you can use to fix the code. 此失败会创建一个可用于修复代码的错误消息。

I would propose routing through a helper that could handle the error. 我建议通过一个可以处理错误的帮助器进行路由。 Something like this which is a variant of this answer 像这样的东西是这个答案的变体

 def safe_image_tag(source, options = {})
    begin
      count = 0
      source ||= "blank-profile-md.png"
      image_tag(source, options)
    rescue Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError
      count += 1
      source = "blank-profile-md.png"
      retry if count < 2
    end
  end

This will in this one case recover and render your default image. 这将在这一情况下恢复并呈现您的默认图像。

i could not agree more with you, raising errors for missing images... i think the asset-pipeline is the most crappy piece of code in rails! 我无法与你达成一致,为丢失的图像引发错误......我认为资产管道是铁轨中最糟糕的代码!

i have some ideas on how you could tackle the problem: 我对如何解决这个问题有一些想法:

you could enable live compilation config.assets.compile = true 你可以启用实时编译config.assets.compile = true

you could catch that error in the helper you are using ( image_tag or whatever) and render a default image. 您可以在正在使用的帮助程序( image_tag或其他)中捕获该错误并呈现默认图像。

you could use rescue_from in your controller if the error is not allover your app. 如果错误不是你的应用程序,你可以在你的控制器中使用rescue_from

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

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