shopify-debugging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Shopify Debugging & Troubleshooting

Shopify调试与故障排除

Expert guidance for debugging Shopify themes, apps, and API integrations with practical solutions to common issues.
针对Shopify主题、应用及API集成调试的专业指南,包含常见问题的实用解决方案。

When to Use This Skill

何时使用本技能

Invoke this skill when:
  • Debugging Liquid template errors or syntax issues
  • Troubleshooting theme rendering problems
  • Fixing API errors (GraphQL, REST)
  • Debugging JavaScript errors in themes or apps
  • Investigating cart or checkout issues
  • Resolving webhook delivery failures
  • Troubleshooting OAuth authentication problems
  • Debugging theme preview or customizer issues
  • Investigating slow page loads or performance problems
  • Fixing metafield or metaobject access errors
  • Resolving CORS or network request issues
在以下场景调用本技能:
  • 调试Liquid模板错误或语法问题
  • 排查主题渲染故障
  • 修复API错误(GraphQL、REST)
  • 调试主题或应用中的JavaScript错误
  • 调查购物车或结账问题
  • 解决Webhook交付失败问题
  • 排查OAuth认证故障
  • 调试主题预览或自定义器问题
  • 调查页面加载缓慢或性能问题
  • 修复元字段(metafield)或元对象(metaobject)访问错误
  • 解决CORS或网络请求问题

Core Capabilities

核心能力

1. Liquid Debugging

1. Liquid调试

Debug Liquid template errors and rendering issues.
Enable Theme Preview:
1. Go to Online Store > Themes
2. Click "Customize" on your theme
3. Open browser DevTools (F12)
4. Check Console for Liquid errors
Common Liquid Errors:
Syntax Error:
liquid
{# ❌ Error: Missing endif #}
{% if product.available %}
  <button>Add to Cart</button>
{# Missing {% endif %} #}

{# ✅ Fixed #}
{% if product.available %}
  <button>Add to Cart</button>
{% endif %}
Undefined Variable:
liquid
{# ❌ Error: product undefined on collection page #}
{{ product.title }}

{# ✅ Fixed: Check context #}
{% if product %}
  {{ product.title }}
{% else %}
  {# Not on product page #}
{% endif %}
Invalid Filter:
liquid
{# ❌ Error: Unknown filter #}
{{ product.price | format_money }}

{# ✅ Fixed: Correct filter name #}
{{ product.price | money }}
Debug Output:
liquid
{# Output variable as JSON #}
{{ product | json }}

{# Check variable type #}
{{ product.class }}

{# Check if variable exists #}
{% if product %}
  Product exists
{% else %}
  Product is nil
{% endif %}

{# Output all properties #}
<pre>{{ product | json }}</pre>
Console Logging from Liquid:
liquid
<script>
  console.log('Product ID:', {{ product.id }});
  console.log('Product data:', {{ product | json }});
  console.log('Cart:', {{ cart | json }});
</script>
调试Liquid模板错误与渲染问题。
启用主题预览:
1. 进入在线商店 > 主题
2. 点击主题的「自定义」
3. 打开浏览器开发者工具(F12)
4. 在控制台中查看Liquid错误
常见Liquid错误:
语法错误:
liquid
{# ❌ 错误:缺少endif #}
{% if product.available %}
  <button>加入购物车</button>
{# 缺少 {% endif %} #}

{# ✅ 修复后 #}
{% if product.available %}
  <button>加入购物车</button>
{% endif %}
未定义变量:
liquid
{# ❌ 错误:在集合页面中product未定义 #}
{{ product.title }}

{# ✅ 修复后:检查上下文 #}
{% if product %}
  {{ product.title }}
{% else %}
  {# 当前并非产品页面 #}
{% endif %}
无效过滤器:
liquid
{# ❌ 错误:未知过滤器 #}
{{ product.price | format_money }}

{# ✅ 修复后:使用正确的过滤器名称 #}
{{ product.price | money }}
调试输出:
liquid
{# 以JSON格式输出变量 #}
{{ product | json }}

{# 检查变量类型 #}
{{ product.class }}

{# 检查变量是否存在 #}
{% if product %}
  产品存在
{% else %}
  产品为nil
{% endif %}

{# 输出所有属性 #}
<pre>{{ product | json }}</pre>
从Liquid输出到控制台:
liquid
<script>
  console.log('产品ID:', {{ product.id }});
  console.log('产品数据:', {{ product | json }});
  console.log('购物车:', {{ cart | json }});
</script>

2. JavaScript Debugging

2. JavaScript调试

Debug JavaScript errors in themes and apps.
Browser Console:
javascript
// Log to console
console.log('Debug:', variable);
console.error('Error:', error);
console.warn('Warning:', warning);

// Log object properties
console.table(data);

// Group related logs
console.group('Cart Operations');
console.log('Cart ID:', cartId);
console.log('Items:', items);
console.groupEnd();

// Time operations
console.time('API Call');
await fetch('/api/data');
console.timeEnd('API Call');

// Stack trace
console.trace('Execution path');
Breakpoints:
javascript
// Programmatic breakpoint
debugger;

// Set in browser DevTools:
// Sources tab > Click line number
Error Handling:
javascript
// ❌ Unhandled error
const data = await fetch('/api/data').then(r => r.json());

// ✅ Proper error handling
try {
  const response = await fetch('/api/data');

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const data = await response.json();
  console.log('Data:', data);
} catch (error) {
  console.error('Failed to fetch data:', error);
  // Show user-friendly error message
  alert('Failed to load data. Please try again.');
}
Network Debugging:
1. Open DevTools > Network tab
2. Filter by XHR or Fetch
3. Click request to see:
   - Request headers
   - Request payload
   - Response headers
   - Response body
   - Timing information
调试主题与应用中的JavaScript错误。
浏览器控制台:
javascript
// 输出到控制台
console.log('调试:', variable);
console.error('错误:', error);
console.warn('警告:', warning);

// 输出对象属性
console.table(data);

// 分组相关日志
console.group('购物车操作');
console.log('购物车ID:', cartId);
console.log('商品:', items);
console.groupEnd();

// 计时操作
console.time('API调用');
await fetch('/api/data');
console.timeEnd('API调用');

// 堆栈跟踪
console.trace('执行路径');
断点:
javascript
// 程序化断点
debugger;

// 在浏览器开发者工具中设置:
// 源代码标签 > 点击行号
错误处理:
javascript
// ❌ 未处理的错误
const data = await fetch('/api/data').then(r => r.json());

// ✅ 正确的错误处理
try {
  const response = await fetch('/api/data');

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const data = await response.json();
  console.log('数据:', data);
} catch (error) {
  console.error('获取数据失败:', error);
  // 显示用户友好的错误信息
  alert('加载数据失败,请重试。');
}
网络调试:
1. 打开开发者工具 > 网络标签
2. 按XHR或Fetch筛选
3. 点击请求查看:
   - 请求头
   - 请求负载
   - 响应头
   - 响应体
   - 计时信息

3. API Error Debugging

3. API错误调试

Debug GraphQL and REST API errors.
GraphQL Errors:
Error response format:
json
{
  "errors": [
    {
      "message": "Field 'invalidField' doesn't exist on type 'Product'",
      "locations": [{ "line": 3, "column": 5 }],
      "path": ["product", "invalidField"],
      "extensions": {
        "code": "FIELD_NOT_FOUND",
        "typeName": "Product"
      }
    }
  ],
  "data": null
}
Check for errors BEFORE accessing data:
javascript
const response = await fetch(graphqlEndpoint, {
  method: 'POST',
  headers: {
    'X-Shopify-Access-Token': accessToken,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query, variables }),
});

const { data, errors } = await response.json();

// ✅ Always check errors first
if (errors) {
  console.error('GraphQL Errors:');
  errors.forEach(error => {
    console.error('Message:', error.message);
    console.error('Location:', error.locations);
    console.error('Path:', error.path);
    console.error('Code:', error.extensions?.code);
  });
  throw new Error(errors[0].message);
}

// Now safe to use data
console.log('Products:', data.products);
Common GraphQL Errors:
Authentication Error:
json
{
  "errors": [{
    "message": "Access denied",
    "extensions": { "code": "UNAUTHENTICATED" }
  }]
}
Fix: Check access token:
javascript
// Verify token is valid
const token = 'shpat_...';

// Check token format (should start with shpat_)
if (!token.startsWith('shpat_')) {
  console.error('Invalid token format');
}

// Verify in headers
headers: {
  'X-Shopify-Access-Token': token,  // ✅ Correct header
  'Authorization': `Bearer ${token}`, // ❌ Wrong for Admin API
}
Field Not Found:
json
{
  "errors": [{
    "message": "Field 'invalidField' doesn't exist on type 'Product'"
  }]
}
Fix: Check field name in API docs:
graphql
undefined
调试GraphQL与REST API错误。
GraphQL错误:
错误响应格式:
json
{
  "errors": [
    {
      "message": "Field 'invalidField' doesn't exist on type 'Product'",
      "locations": [{ "line": 3, "column": 5 }],
      "path": ["product", "invalidField"],
      "extensions": {
        "code": "FIELD_NOT_FOUND",
        "typeName": "Product"
      }
    }
  ],
  "data": null
}
在访问数据前先检查错误:
javascript
const response = await fetch(graphqlEndpoint, {
  method: 'POST',
  headers: {
    'X-Shopify-Access-Token': accessToken,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query, variables }),
});

const { data, errors } = await response.json();

// ✅ 始终先检查错误
if (errors) {
  console.error('GraphQL错误:');
  errors.forEach(error => {
    console.error('信息:', error.message);
    console.error('位置:', error.locations);
    console.error('路径:', error.path);
    console.error('代码:', error.extensions?.code);
  });
  throw new Error(errors[0].message);
}

// 现在可以安全使用数据
console.log('产品:', data.products);
常见GraphQL错误:
认证错误:
json
{
  "errors": [{
    "message": "Access denied",
    "extensions": { "code": "UNAUTHENTICATED" }
  }]
}
修复: 检查访问令牌
javascript
// 验证令牌是否有效
const token = 'shpat_...';

// 检查令牌格式(应以shpat_开头)
if (!token.startsWith('shpat_')) {
  console.error('无效的令牌格式');
}

// 验证请求头
headers: {
  'X-Shopify-Access-Token': token,  // ✅ 正确的请求头
  'Authorization': `Bearer ${token}`, // ❌ 不适用于Admin API
}
字段不存在:
json
{
  "errors": [{
    "message": "Field 'invalidField' doesn't exist on type 'Product'"
  }]
}
修复: 在API文档中检查字段名称
graphql
undefined

❌ Wrong field name

❌ 错误的字段名称

query { product(id: "gid://shopify/Product/123") { invalidField } }
query { product(id: "gid://shopify/Product/123") { invalidField } }

✅ Correct field name

✅ 正确的字段名称

query { product(id: "gid://shopify/Product/123") { title handle status } }

**Rate Limit Error:**
```javascript
// Check rate limit header
const response = await fetch(graphqlEndpoint, options);

const rateLimit = response.headers.get('X-Shopify-GraphQL-Admin-Api-Call-Limit');
console.log('Rate limit:', rateLimit); // "42/50"

if (response.status === 429) {
  const retryAfter = response.headers.get('Retry-After');
  console.log(`Rate limited. Retry after ${retryAfter} seconds`);
}
REST API Errors:
404 Not Found:
javascript
const response = await fetch(`https://${shop}/admin/api/2025-10/products/999999.json`, {
  headers: { 'X-Shopify-Access-Token': token },
});

if (response.status === 404) {
  console.error('Product not found');
  // Check:
  // 1. Product ID is correct
  // 2. Product exists in store
  // 3. Using correct endpoint
}
422 Unprocessable Entity:
json
{
  "errors": {
    "title": ["can't be blank"],
    "price": ["must be greater than 0"]
  }
}
Fix: Validate input:
javascript
const response = await fetch(endpoint, {
  method: 'POST',
  headers: {
    'X-Shopify-Access-Token': token,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    product: {
      title: '',  // ❌ Empty title
      price: -10, // ❌ Negative price
    },
  }),
});

if (response.status === 422) {
  const { errors } = await response.json();
  console.error('Validation errors:', errors);

  // Fix data
  const validProduct = {
    title: 'Product Name',  // ✅ Valid title
    price: 19.99,           // ✅ Valid price
  };
}
query { product(id: "gid://shopify/Product/123") { title handle status } }

**速率限制错误:**
```javascript
// 检查速率限制请求头
const response = await fetch(graphqlEndpoint, options);

const rateLimit = response.headers.get('X-Shopify-GraphQL-Admin-Api-Call-Limit');
console.log('速率限制:', rateLimit); // "42/50"

if (response.status === 429) {
  const retryAfter = response.headers.get('Retry-After');
  console.log(`已触发速率限制,${retryAfter}秒后重试`);
}
REST API错误:
404 未找到:
javascript
const response = await fetch(`https://${shop}/admin/api/2025-10/products/999999.json`, {
  headers: { 'X-Shopify-Access-Token': token },
});

if (response.status === 404) {
  console.error('产品未找到');
  // 检查:
  // 1. 产品ID是否正确
  // 2. 产品是否存在于店铺中
  // 3. 是否使用了正确的端点
}
422 无法处理的实体:
json
{
  "errors": {
    "title": ["can't be blank"],
    "price": ["must be greater than 0"]
  }
}
修复: 验证输入内容
javascript
const response = await fetch(endpoint, {
  method: 'POST',
  headers: {
    'X-Shopify-Access-Token': token,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    product: {
      title: '',  // ❌ 标题为空
      price: -10, // ❌ 价格为负数
    },
  }),
});

if (response.status === 422) {
  const { errors } = await response.json();
  console.error('验证错误:', errors);

  // 修复数据
  const validProduct = {
    title: '产品名称',  // ✅ 有效的标题
    price: 19.99,           // ✅ 有效的价格
  };
}

4. Cart Debugging

4. 购物车调试

Debug cart and Ajax API issues.
Cart Not Updating:
javascript
// ❌ Common mistake: Wrong variant ID
fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: '123',  // ❌ Wrong: using product ID instead of variant ID
    quantity: 1,
  }),
});

// ✅ Fixed: Use variant ID
fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: 123456789,  // ✅ Variant ID (numeric)
    quantity: 1,
  }),
})
  .then(response => {
    if (!response.ok) {
      return response.json().then(err => {
        console.error('Cart error:', err);
        throw err;
      });
    }
    return response.json();
  })
  .then(item => {
    console.log('Added to cart:', item);
    // Update cart UI
  })
  .catch(error => {
    console.error('Failed to add to cart:', error);
  });
Get Current Cart:
javascript
// Debug current cart state
fetch('/cart.js')
  .then(r => r.json())
  .then(cart => {
    console.log('Cart:', cart);
    console.log('Item count:', cart.item_count);
    console.log('Total:', cart.total_price);
    console.log('Items:', cart.items);

    cart.items.forEach(item => {
      console.log('Item:', item.product_id, item.variant_id, item.quantity);
    });
  });
Cart AJAX Errors:
javascript
// Common error: Insufficient inventory
{
  "status": 422,
  "message": "You can only add 5 of this item to your cart",
  "description": "Cannot add more than 5 to cart"
}

// Fix: Check inventory before adding
const variant = product.variants.find(v => v.id === variantId);

if (variant.inventory_quantity < quantity) {
  alert(`Only ${variant.inventory_quantity} available`);
} else {
  // Add to cart
}
调试购物车与Ajax API问题。
购物车未更新:
javascript
// ❌ 常见错误:错误的变体ID
fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: '123',  // ❌ 错误:使用产品ID而非变体ID
    quantity: 1,
  }),
});

// ✅ 修复后:使用变体ID
fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: 123456789,  // ✅ 变体ID(数值型)
    quantity: 1,
  }),
})
  .then(response => {
    if (!response.ok) {
      return response.json().then(err => {
        console.error('购物车错误:', err);
        throw err;
      });
    }
    return response.json();
  })
  .then(item => {
    console.log('已加入购物车:', item);
    // 更新购物车UI
  })
  .catch(error => {
    console.error('加入购物车失败:', error);
  });
获取当前购物车:
javascript
// 调试当前购物车状态
fetch('/cart.js')
  .then(r => r.json())
  .then(cart => {
    console.log('购物车:', cart);
    console.log('商品数量:', cart.item_count);
    console.log('总价:', cart.total_price);
    console.log('商品:', cart.items);

    cart.items.forEach(item => {
      console.log('商品:', item.product_id, item.variant_id, item.quantity);
    });
  });
购物车AJAX错误:
javascript
// 常见错误:库存不足
{
  "status": 422,
  "message": "You can only add 5 of this item to your cart",
  "description": "Cannot add more than 5 to cart"
}

// 修复:加入前检查库存
const variant = product.variants.find(v => v.id === variantId);

if (variant.inventory_quantity < quantity) {
  alert(`仅剩${variant.inventory_quantity}件库存`);
} else {
  // 加入购物车
}

5. Theme Preview Debugging

5. 主题预览调试

Debug issues in the theme customizer.
Theme Editor Console:
1. Open theme customizer
2. Open DevTools (F12)
3. Check Console for errors
4. Look for:
   - Liquid errors (red text)
   - JavaScript errors
   - Network failures
Section Not Rendering:
liquid
{# Check section schema #}
{% schema %}
{
  "name": "My Section",
  "settings": [...]  {# ✅ Must have settings #}
}
{% endschema %}

{# ❌ Missing schema = won't show in customizer #}
Settings Not Updating:
liquid
{# ❌ Wrong: Using hardcoded value #}
<h1>Hardcoded Title</h1>

{# ✅ Fixed: Use setting #}
<h1>{{ section.settings.title }}</h1>

{% schema %}
{
  "name": "Hero",
  "settings": [
    {
      "type": "text",
      "id": "title",
      "label": "Title",
      "default": "Welcome"
    }
  ]
}
{% endschema %}
Block Attributes Missing:
liquid
{# ❌ Missing shopify_attributes #}
<div class="block">
  {{ block.settings.text }}
</div>

{# ✅ Fixed: Add shopify_attributes for theme editor #}
<div class="block" {{ block.shopify_attributes }}>
  {{ block.settings.text }}
</div>
调试主题自定义器中的问题。
主题编辑器控制台:
1. 打开主题自定义器
2. 打开开发者工具(F12)
3. 在控制台中检查错误
4. 重点关注:
   - Liquid错误(红色文本)
   - JavaScript错误
   - 网络请求失败
区块未渲染:
liquid
{# 检查区块schema #}
{% schema %}
{
  "name": "我的区块",
  "settings": [...]  {# ✅ 必须包含settings #}
}
{% endschema %}

{# ❌ 缺少schema将不会在自定义器中显示 #}
设置未更新:
liquid
{# ❌ 错误:使用硬编码值 #}
<h1>硬编码标题</h1>

{# ✅ 修复后:使用设置值 #}
<h1>{{ section.settings.title }}</h1>

{% schema %}
{
  "name": "首页横幅",
  "settings": [
    {
      "type": "text",
      "id": "title",
      "label": "标题",
      "default": "欢迎光临"
    }
  ]
}
{% endschema %}
区块属性缺失:
liquid
{# ❌ 缺少shopify_attributes #}
<div class="block">
  {{ block.settings.text }}
</div>

{# ✅ 修复后:添加shopify_attributes以支持主题编辑器 #}
<div class="block" {{ block.shopify_attributes }}>
  {{ block.settings.text }}
</div>

6. Webhook Debugging

6. Webhook调试

Debug webhook delivery and processing.
Webhook Not Received:
Check in Shopify Admin:
1. Settings > Notifications > Webhooks
2. Click webhook
3. Check "Recent deliveries"
4. Look for delivery status:
   - ✅ Success (200 OK)
   - ❌ Failed (4xx/5xx errors)
Verify Webhook HMAC:
javascript
import crypto from 'crypto';

function verifyWebhook(body, hmac, secret) {
  const hash = crypto
    .createHmac('sha256', secret)
    .update(body, 'utf8')
    .digest('base64');

  return hash === hmac;
}

// Express example
app.post('/webhooks/orders', (req, res) => {
  const hmac = req.headers['x-shopify-hmac-sha256'];
  const body = JSON.stringify(req.body);

  if (!verifyWebhook(body, hmac, process.env.SHOPIFY_WEBHOOK_SECRET)) {
    console.error('Invalid webhook HMAC');
    return res.status(401).send('Unauthorized');
  }

  console.log('Webhook verified');

  // Process webhook
  const order = req.body;
  console.log('Order:', order.id, order.email);

  // Respond quickly (< 5 seconds)
  res.status(200).send('OK');
});
Webhook Timeout:
javascript
// ❌ Processing takes too long (> 5 seconds)
app.post('/webhooks/orders', async (req, res) => {
  await processOrder(req.body);  // Slow operation
  res.send('OK');  // Response delayed
});

// ✅ Respond immediately, process async
app.post('/webhooks/orders', async (req, res) => {
  const order = req.body;

  // Respond quickly
  res.status(200).send('OK');

  // Process in background
  processOrder(order).catch(console.error);
});
调试Webhook交付与处理问题。
未收到Webhook:
在Shopify后台检查:
1. 设置 > 通知 > Webhook
2. 点击对应的Webhook
3. 查看「最近交付记录」
4. 检查交付状态:
   - ✅ 成功(200 OK)
   - ❌ 失败(4xx/5xx错误)
验证Webhook HMAC:
javascript
import crypto from 'crypto';

function verifyWebhook(body, hmac, secret) {
  const hash = crypto
    .createHmac('sha256', secret)
    .update(body, 'utf8')
    .digest('base64');

  return hash === hmac;
}

// Express示例
app.post('/webhooks/orders', (req, res) => {
  const hmac = req.headers['x-shopify-hmac-sha256'];
  const body = JSON.stringify(req.body);

  if (!verifyWebhook(body, hmac, process.env.SHOPIFY_WEBHOOK_SECRET)) {
    console.error('无效的Webhook HMAC');
    return res.status(401).send('未授权');
  }

  console.log('Webhook已验证');

  // 处理Webhook
  const order = req.body;
  console.log('订单:', order.id, order.email);

  // 快速响应(<5秒)
  res.status(200).send('OK');
});
Webhook超时:
javascript
// ❌ 处理时间过长(>5秒)
app.post('/webhooks/orders', async (req, res) => {
  await processOrder(req.body);  // 缓慢操作
  res.send('OK');  // 响应延迟
});

// ✅ 立即响应,异步处理
app.post('/webhooks/orders', async (req, res) => {
  const order = req.body;

  // 快速响应
  res.status(200).send('OK');

  // 在后台处理
  processOrder(order).catch(console.error);
});

7. Common Error Messages

7. 常见错误信息

Liquid Errors:
Error: Liquid syntax error: Unknown tag 'section'
Fix: Use {% section %} only in JSON templates, not .liquid files
Error: undefined method 'title' for nil:NilClass
Fix: Variable is nil. Add {% if %} check or provide default:
{{ product.title | default: "No title" }}
Error: Exceeded maximum number of allowed iterations
Fix: Infinite loop detected. Check loop conditions.
JavaScript Errors:
TypeError: Cannot read property 'forEach' of undefined
Fix: Array is undefined. Check:
if (items && Array.isArray(items)) {
  items.forEach(item => { ... });
}
ReferenceError: $ is not defined
Fix: jQuery not loaded or script runs before jQuery loads
SyntaxError: Unexpected token <
Fix: API returned HTML error page instead of JSON. Check API endpoint.
API Errors:
Access denied - check your access scopes
Fix: App needs additional permissions. Update scopes in Partner Dashboard.
Throttled: Exceeded API rate limit
Fix: Implement rate limit handling with exponential backoff.
Field doesn't exist on type
Fix: Check API version and field availability in docs.
Liquid错误:
Error: Liquid syntax error: Unknown tag 'section'
修复:仅在JSON模板中使用{% section %},不要在.liquid文件中使用
Error: undefined method 'title' for nil:NilClass
修复:变量为nil。添加{% if %}检查或提供默认值:
{{ product.title | default: "无标题" }}
Error: Exceeded maximum number of allowed iterations
修复:检测到无限循环。检查循环条件。
JavaScript错误:
TypeError: Cannot read property 'forEach' of undefined
修复:数组未定义。检查:
if (items && Array.isArray(items)) {
  items.forEach(item => { ... });
}
ReferenceError: $ is not defined
修复:jQuery未加载或脚本在jQuery加载前执行
SyntaxError: Unexpected token <
修复:API返回HTML错误页面而非JSON。检查API端点。
API错误:
Access denied - check your access scopes
修复:应用需要额外权限。在合作伙伴后台更新权限范围。
Throttled: Exceeded API rate limit
修复:实现带指数退避的速率限制处理。
Field doesn't exist on type
修复:检查API版本及字段在文档中的可用性。

Debugging Toolkit

调试工具包

Browser DevTools:
- Console: View errors and logs
- Network: Inspect API requests
- Sources: Set breakpoints
- Application: View cookies, localStorage
- Performance: Profile page load
Shopify Tools:
- Theme Preview: Test changes before publishing
- Theme Inspector: View section data
- API Explorer: Test GraphQL queries
- Webhook Logs: Check delivery status
Useful Console Commands:
javascript
// Get all form data
new FormData(document.querySelector('form'))

// View all cookies
document.cookie

// Check localStorage
localStorage

// View all global variables
console.log(window)

// Get computed styles
getComputedStyle(element)
浏览器开发者工具:
- 控制台:查看错误与日志
- 网络:检查API请求
- 源代码:设置断点
- 应用:查看Cookie、localStorage
- 性能:分析页面加载
Shopify工具:
- 主题预览:发布前测试更改
- 主题检查器:查看区块数据
- API Explorer:测试GraphQL查询
- Webhook日志:检查交付状态
实用控制台命令:
javascript
// 获取所有表单数据
new FormData(document.querySelector('form'))

// 查看所有Cookie
document.cookie

// 检查localStorage
localStorage

// 查看所有全局变量
console.log(window)

// 获取计算样式
getComputedStyle(element)

Best Practices

最佳实践

  1. Always check for errors before accessing data (API responses)
  2. Use try-catch blocks for all async operations
  3. Log meaningful messages with context
  4. Verify HMAC for all webhooks
  5. Test in theme preview before publishing
  6. Monitor API rate limits and implement backoff
  7. Handle edge cases (nil values, empty arrays)
  8. Use browser DevTools for network debugging
  9. Check API version compatibility
  10. Validate input before API calls
  1. 访问数据前始终检查错误(API响应)
  2. 对所有异步操作使用try-catch块
  3. 记录包含上下文的有意义信息
  4. 验证所有Webhook的HMAC
  5. 发布前在主题预览中测试
  6. 监控API速率限制并实现退避机制
  7. 处理边缘情况(nil值、空数组)
  8. 使用浏览器开发者工具进行网络调试
  9. 检查API版本兼容性
  10. API调用前验证输入内容

Integration with Other Skills

与其他技能的集成

  • shopify-liquid - Use when debugging Liquid template code
  • shopify-api - Use when debugging API calls
  • shopify-theme-dev - Use when debugging theme structure issues
  • shopify-app-dev - Use when debugging custom apps
  • shopify-performance - Use when debugging slow performance
  • shopify-liquid - 调试Liquid模板代码时使用
  • shopify-api - 调试API调用时使用
  • shopify-theme-dev - 调试主题结构问题时使用
  • shopify-app-dev - 调试自定义应用时使用
  • shopify-performance - 调试性能缓慢问题时使用

Quick Reference

快速参考

javascript
// Debug Liquid
{{ variable | json }}
{% if variable %}{{ variable }}{% endif %}

// Debug JavaScript
console.log('Debug:', data);
debugger;

// Debug API
const { data, errors } = await response.json();
if (errors) console.error(errors);

// Debug Cart
fetch('/cart.js').then(r => r.json()).then(console.log);

// Debug Webhooks
const valid = verifyHmac(body, hmac, secret);
console.log('Webhook valid:', valid);
javascript
// 调试Liquid
{{ variable | json }}
{% if variable %}{{ variable }}{% endif %}

// 调试JavaScript
console.log('调试:', data);
debugger;

// 调试API
const { data, errors } = await response.json();
if (errors) console.error(errors);

// 调试购物车
fetch('/cart.js').then(r => r.json()).then(console.log);

// 调试Webhook
const valid = verifyHmac(body, hmac, secret);
console.log('Webhook验证通过:', valid);