Skip to content

错误处理示例

演示 SDK 的 10 种错误类型和 instanceof 类型窄化。

在线演示

源码

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TopBridge SDK — Error Handling Example</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 800px; margin: 40px auto; padding: 0 20px; }
    h1 { color: #333; }
    .section { margin: 20px 0; padding: 16px; border: 1px solid #ddd; border-radius: 8px; }
    button { padding: 8px 16px; margin: 4px; cursor: pointer; border: 1px solid #ccc; border-radius: 4px; background: #fff; }
    button:hover { background: #f0f0f0; }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
    #log { background: #1a1a1a; color: #0f0; padding: 16px; border-radius: 8px; font-family: monospace;
           font-size: 13px; max-height: 400px; overflow-y: auto; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h1>Error Handling Example</h1>
  <p>Demonstrates SDK error types and <code>instanceof</code> narrowing.</p>

  <div class="section">
    <h2>1. Preflight Error Handling</h2>
    <button onclick="runPreflightWithErrorHandling()">Run Preflight (with error handling)</button>
  </div>

  <div class="section">
    <h2>2. Print Validation Error</h2>
    <button onclick="runPrintWithEmptyProducts()">Empty Product List (trigger ValidationError)</button>
  </div>

  <div class="section">
    <h2>Log</h2>
    <div id="log"></div>
  </div>

  <script type="module">
    const {
      TopBridgeClient,
      TopBridgeConnectionError,
      TopBridgeAuthError,
      TopBridgeQuotaError,
      TopBridgePrintError,
      TopBridgeValidationError,
      TopBridgePrinterError,
      TopBridgeTemplateError,
      TopBridgeNetworkError,
      TopBridgeSourceError,
    } = await import('https://esm.sh/@appzgatenz/label-print-topbridge-js')

    function log(msg) {
      const el = document.getElementById('log')
      const time = new Date().toLocaleTimeString()
      el.textContent += `[${time}] ${msg}\n`
      el.scrollTop = el.scrollHeight
    }

    function logError(err) {
      log(`  ❌ ${err.constructor.name}: ${err.message}`)
      if (err.code) log(`     code: ${err.code}`)
      if (err.field) log(`     field: ${err.field}`)
      if (err.reason) log(`     reason: ${err.reason}`)
      if (err.storeUrl) log(`     storeUrl: ${err.storeUrl}`)
    }

    window.runPreflightWithErrorHandling = async () => {
      log('--- Running preflight (with full error handling) ---')
      const client = new TopBridgeClient({ debug: true })

      try {
        const preflight = await client.preflight.run({
          onStepChange: (step) => log(`  Step: ${step}...`)
        })
        log('✓ Preflight passed')
        log(`  Printer: ${preflight.printers.data?.defaultPrinter}`)
      } catch (err) {
        if (err instanceof TopBridgeConnectionError) {
          logError(err)
          log('  💡 Suggestion: Make sure the TopBridge desktop app is running')
        } else if (err instanceof TopBridgeAuthError) {
          logError(err)
          if (err.code === 'UPDATE_REQUIRED') {
            log('  💡 Suggestion: Please update TopBridge')
            if (err.storeUrl) log(`  Update link: ${err.storeUrl}`)
          } else {
            log('  💡 Suggestion: Please log in to the TopBridge desktop app first')
          }
        } else if (err instanceof TopBridgeQuotaError) {
          logError(err)
          log('  💡 Suggestion: Insufficient print quota, please contact your administrator')
        } else if (err instanceof TopBridgePrinterError) {
          logError(err)
          log('  💡 Suggestion: Please check if the printer is online and the protocol (TSPL/ZPL) is configured')
        } else {
          logError(err)
        }
      }
    }

    window.runPrintWithEmptyProducts = async () => {
      log('--- Empty product list test ---')
      const client = new TopBridgeClient()

      try {
        await client.print.execute({
          template: 'PRICE_LABEL',
          printer: 'Test',
          products: [],
        })
      } catch (err) {
        if (err instanceof TopBridgeValidationError) {
          logError(err)
          log('  💡 Validation failed: products cannot be an empty array')
        } else {
          logError(err)
        }
      }
    }

    // --- iframe height auto-resize ---
    function reportHeight() {
      const height = document.documentElement.scrollHeight
      window.parent.postMessage({ type: 'resize-iframe', height }, '*')
    }
    window.addEventListener('load', reportHeight)
    window.addEventListener('resize', reportHeight)
    const observer = new MutationObserver(reportHeight)
    observer.observe(document.body, { childList: true, subtree: true })
  </script>
</body>
</html>