【问题标题】:Rescue_from is not workingRescue_from 不起作用
【发布时间】:2017-12-23 05:07:48
【问题描述】:

我在加载图像时尝试处理路由错误,但有些图像丢失了。

你知道我只想用默认图像图标替换丢失的图像并抑制错误消息。

所以我尝试了

class ImagesController < ApplicationController
       [...]

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

      [...]
 end

然后我得到了这个:

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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails controller rescue


    【解决方案1】:

    您可以使用rescue_from 方法rescue_from除服务器错误之外的任何类型的异常。你把这个方法写在你的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
    

    render 'default_image_here' 你可以使用这个:

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

    这会将文件读取为二进制而不是文本。

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2016-08-29
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      相关资源
      最近更新 更多