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

我做错什么了吗?

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

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

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

在这种情况下,您可以使用regexe.message.match?(/404 Not Found/),但我更喜欢以上的方法

弄清楚了这一点,因为它也一直困扰着我。您可以通过传入: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

Oli的回复为我指明了正确的方向,这一条为我完成了任务:

ShopifyAPI::Product.all(ids: member.shopify_id).first

然后检查是否为零。

最新更新