简体   繁体   English

Rescue_from不起作用

[英]Rescue_from is not working

I was trying to handle routing error when I'm loading images and some are missing. 加载图像时我试图处理路由错误,但缺少一些图像。

You know I wanted just to replace a missing image with the default image icon and to suppress error message. 您知道我只想用默认的图像图标替换丢失的图像并消除错误消息。

So I tried 所以我尝试了

class ImagesController < ApplicationController
       [...]

       def index
         images = Image.all
         rescue_from ActionController::RoutingError, with: :image_route_error
       end

      [...]
 end

Then I got this: 然后我得到了这个:

NoMethodError (undefined method `rescue_from' for #<ImagesController:0x007fe382227e38>
Did you mean?  rescue_handlers):

Any ideas? 有任何想法吗?

You can rescue_from any kind of exceptions other than server errors using rescue_from method. 您可以使用rescue_from方法从服务器错误以外的任何种类的resurance_from异常。 You write this method in your ApplicationController . 您可以在ApplicationController编写此方法。

rescue_from ActionController::RoutingError do |exception|
    if controller_name == "image" && action_name == "index"
           render 'default_image_here', status: 200 
    else
     render plain: 'Not found', status: 400 
   end
end

In render 'default_image_here' you can use this: render 'default_image_here'您可以使用以下命令:

render :text => open(image_url, "rb").read, status: 200

This will read file as binary instead of text. 这会将文件读取为二进制文件而不是文本文件。

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

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