web-print-pdf frontend error handling — standard reference

Silent printing spans browser → WebSocket → local client → printer. This guide shows how to tell connection issues from print failures, use formatPrintError for user-facing messages, and work through production checklists.

Three error layers—know the source; one catch is fine

Layer When it fires How to tell
Transport Client not running, port blocked, WS dropped Promise reject; message usually connection-related; optional getConnectStatus() preflight
Business Connected but render/print failed Reject object with success: false and message
Application Invalid params, missing await, hard-coded printer name Fails before the SDK call or before print starts
The table is for troubleshooting, not three separate catch blocks. Recommended: one try/catch around preflight and print, unified formatPrintError(err) (see examples below). Optional onError for global disconnect monitoring alongside button-level catch.

Standard response shapes

Every WS reply has id, type, timestamp, success. The npm package matches by id: resolve on true, reject the whole message object on false (not an Error instance).

Failure example:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": 1710000001000,
  "type": "printHtml",
  "success": false,
  "message": "printing exited with exit code: 1",
  "data": null
}

Success example:

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": 1710000001000,
  "type": "printHtml",
  "success": true,
  "data": { "pdfPath": "...", "pdfUrl": "...", "pdfFileName": "..." },
  "extraOptions": { "action": "print" }
}

Unified error messages (copy-paste)

On failure the SDK may reject with the whole message object (not an Error)—alert(err) often shows [object Object]. Copy the single function below (e.g. src/utils/print-error.js) and use it in catch for user-facing text.

/** 把 reject / 异常转成可展示的字符串 */
export function formatPrintError(err, fallback = '未知错误') {
  if (!err) return fallback;
  if (typeof err === 'string') return err;
  if (err instanceof Error && err.message) return err.message;
  if (typeof err === 'object' && err !== null) {
    if (typeof err.message === 'string' && err.message) return err.message;
    if (typeof err.msg === 'string' && err.msg) return err.msg;
  }
  try { return JSON.stringify(err); } catch { return String(err); }
}

In your app (same as live demos):

import webPrintPdf from 'web-print-pdf';
import { formatPrintError } from './print-error.js';

async function onPrintClick() {
  try {
    const status = await webPrintPdf.utils.getConnectStatus();
    if (status.success !== true) throw status;

    const result = await webPrintPdf.printHtml(
      document.getElementById('area').innerHTML,
      { paperFormat: 'A4', printBackground: true },
      { paperFormat: 'A4' },
      { action: 'print', requestTimeout: 15 }
    );
    console.log('打印成功', result);
  } catch (err) {
    alert(formatPrintError(err)); // 或 toast / ElMessage
  }
}

Wrap printHtmlByUrl, batchPrint, getPrinterList, etc. in the same try/catch and call formatPrintError(err) on failure. No separate preflight handler—if getConnectStatus fails, throw status and use the same catch as print errors.

Use success === true on getConnectStatus (verified: data is often boolean true, not { connected: true }). Connection, preflight, and print failures all go through formatPrintError.

onResponse and onError

Besides Promises, register global callbacks for logs, analytics, or UI:

// 所有回包(成功 + 失败)都会触发
webPrintPdf.utils.onResponse((msg) => {
  console.log('[print-ws]', msg.type, msg.success, msg.message || '');
});

// 仅 WebSocket 传输错误(如连接异常)
webPrintPdf.utils.onError((e) => {
  console.error('[print-ws-error]', e);
});
APIScopeUse case
try/catchSingle callButton clicks—immediate user feedback
onResponseEvery WS replyAudit logs, debugging, success rate
onErrorWS transportDisconnect monitoring, “restart client” hints
Business failures (success:false) reject Promises and hit onResponse—they may not call onError. Do not rely on onError alone for print success.

Common failures and fixes

Symptom / message Likely cause What to do
WebSocket connection failed / connection refused Client not running or port in use Start client; verify port in UI; avoid multiple instances
websocket has not been connected Missing await, requests before connect completes Always await APIs; no fire-and-forget chains
printing exited with exit code: 1 / print failed Invalid printerName with action print; preview may fall back to default without error Call getPrinterList() first; validate printers with action: 'print', not preview alone
Preview OK but wrong printer used Bad printerName may be ignored in preview mode Verify with print before production; or omit printerName to use default explicitly
URL load timeout Slow intranet page, short requestTimeout Raise extraOptions.requestTimeout; check cookies/headers
Invalid params / watermark rejected Invalid pdfOptions See print options guide: rgb colors, angle ≥ 0, etc.
batchPrint partial failure One task has bad params or content Check client Logs tab; split batch to isolate task

Vue 3 example

import { ref } from 'vue';
import webPrintPdf from 'web-print-pdf';
import { formatPrintError } from './print-error.js';

export function usePrintWithError() {
  const loading = ref(false);
  const lastError = ref('');

  async function printHtml(html, pdfOptions, printOptions, extraOptions) {
    loading.value = true;
    lastError.value = '';
    try {
      const status = await webPrintPdf.utils.getConnectStatus();
      if (status.success !== true) throw status;
      return await webPrintPdf.printHtml(html, pdfOptions, printOptions, extraOptions);
    } catch (err) {
      lastError.value = formatPrintError(err);
      return null;
    } finally {
      loading.value = false;
    }
  }

  return { loading, lastError, printHtml };
}

Bind lastError to your toast and loading to disable the button.

Production checklist

  1. DevTools: WS to ws://127.0.0.1:port/websocket/standard
  2. Client Logs tab shows failure for the same id
  3. Try action: 'preview' first, then tune printOptions
  4. Reproduce on another machine to rule out drivers
  5. Run connection demo on live demos and compare
Download client free Open live demos