首页 > 解决方案 > Shopify:从 ShopfyAPI 捕获 RestAPI 调用的异常

问题描述

我试图捕获一个异常,当找不到某个 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-railsshopify

解决方案


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

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

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

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


推荐阅读