【问题标题】:How to handle exceptions for multiple URLs如何处理多个 URL 的异常
【发布时间】:2018-01-29 21:03:38
【问题描述】:

为了获得我这样写的网站图标二进制文件。

  def favicon_url_from_link
     # get a url from link tag
    URI('http://example.com/common/favicon.png')
  end

  def favicon_url_from_path
    URI('http://example.com/favicon.ico')
  end

  def favicon_binary_from_link
    favicon_url_from_link&.read
  rescue OpenURI::HTTPError
    nil
  end

  def favicon_binary_from_path
    favicon_url_from_path&.read
  rescue OpenURI::HTTPError
    nil
  end

  def favicon_binary
    favicon_binary_from_link || favicon_binary_from_path
  end

但我认为为每个 url 编写 rescue 子句有点多余。 怎么写更简洁?

【问题讨论】:

    标签: ruby exception


    【解决方案1】:

    一种方法是将引发异常的部分提取到单独的方法中,例如read_url

    def favicon_binary_from_link
      read_url(favicon_url_from_link)
    end
    
    def favicon_binary_from_path
      read_url(favicon_url_from_path)
    end
    
    def read_url(url)
      url&.read
    rescue OpenURI::HTTPError
      nil
    end
    
    def favicon_binary
      favicon_binary_from_link || favicon_binary_from_path
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2011-02-03
      • 2010-12-14
      相关资源
      最近更新 更多