You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用shopify_api调用GraphQL productByHandle查询返回nil时报错

报错原因说明
  • 第一个NoMethodError报错:这是Shopify GraphQL Ruby客户端依赖的graphql-client gem的固有行为:当顶层查询字段productByHandle返回null时,返回的data包装对象不会生成对应的.productByHandle属性访问方法,直接调用点语法就会触发方法不存在的错误。
  • 第二个GraphQL::Client::ValidationError报错:Shopify官方GraphQL接口定义的productByHandle查询的handle参数本身就是非空必填的String!类型,你将查询变量改为可空的String后,变量类型和参数要求不匹配,就会触发类型校验错误,变量类型必须保持为String!,不能修改。
解决方案

不要用点语法直接访问可能返回null的查询字段,改用哈希取值方式获取字段值,同时先处理查询层面的报错即可,正确代码示例如下:

client = ShopifyAPI::GraphQL.client
product_handle_query = client.parse <<-'GRAPHQL'
 query ($productHandle: String!) {
  productByHandle(handle: $productHandle) {
    id
    handle
    title
    tags
    productType
    vendor
  }
}
GRAPHQL
result = client.query(product_handle_query, variables: {productHandle: productHandle})

# 优先处理查询执行错误
if result.errors.any?
  # 自定义错误处理逻辑,例如打印错误信息
  puts result.errors.full_messages
else
  # 用哈希取值方式获取字段,无对应商品时会正常返回nil
  product = result.data[:productByHandle]
  puts product
end

如果更习惯用点语法访问,也可以先判断属性是否存在再调用:

product = result.data.respond_to?(:productByHandle) ? result.data.productByHandle : nil

内容的提问来源于stack exchange,提问作者JessiDeuxTrois

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:42:07