【问题标题】:Shopify: catching exceptions of RestAPI calls from the ShopfyAPIShopify:从 ShopfyAB 捕获 Rest API 调用的异常
【发布时间】:2018-12-03 11:42:35
【问题描述】:

我试图捕获一个异常,当找不到某个 id 时,但应用程序仍然停止并显示以下消息: ActiveResource::ResourceNotFound

代码如下:

begin
  ShopifyAPI::ScriptTag.find(x.scriptid)
rescue => e
  if e.message == '404 Not Found'
  # handle 404 error
  else
    raise e
  end
end

我是不是做错了什么?

【问题讨论】:

    标签: ruby-on-rails shopify


    【解决方案1】:

    这里更好的做法是挽救您想要的异常,而不是 StandardError

    rescue ActiveResource::ResourceNotFound => e
      # handle 404 error
    end
    

    我不能马上说为什么你的例子不起作用,但我猜这个消息不完全是404 Not Found

    在这种情况下您可以使用正则表达式 e.message.match?(/404 Not Found/),但我更喜欢上面的方法

    【讨论】:

    • 谢谢,问题是消息不完全是“404 Not found”
    • 错误对象也带有代码。代码通常很精确,也为您提供了一种处理问题的方法。
    【解决方案2】:

    想出了这个,因为它也一直在困扰着我。 您可以通过传入 :all 和 id 的参数来向 Shopify API 索取一个集合。如果它返回一个空数组,则只需手动引发错误。

    begin
      @product = ShopifyAPI::Product.find(:all, params: { ids: product_id })&.first || raise('Shopify product not found')
    rescue => e
      puts e.message and return false
    end
    

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多