whereparcel

何か聞きたいことがあれば、気軽にどうぞ。WhereParcelを作った開発者が直接メッセージを読んで返信します。

ガイド 9 分で読めます

追跡例外の処理:開発者向けエッジケースガイド

配達失敗、通関保留、住所不備など、荷物追跡における例外処理の方法を解説します。堅牢なアプリケーションを構築するための実践的なパターンをご紹介します。

WhereParcel Team

理想的な世界では、すべての荷物が集荷から配達までスムーズに届けられるでしょう。しかし現実には、配送の5〜15%で例外が発生します。配達失敗、通関保留、荷物の破損、住所の問題など、さまざまなケースがあります。アプリケーションがこれらの例外をどのように処理するかによって、お客様が配送体験を信頼するか、サポート窓口に問い合わせが殺到するかが決まります。

よくある追跡例外の種類

例外のカテゴリを理解することで、それぞれに適切な処理を構築できます。

配達例外

USPSで不在により配達できなかったとき、data.events の最後の要素は次のようになります(イベントは古い順に並ぶため、最新のイベントは配列の末尾です)。

{
  "timestamp": "2026-01-18T14:30:00-06:00",
  "status": "in_transit",
  "location": "CHICAGO, IL 60607",
  "description": "Notice Left (No Authorized Recipient Available)",
  "rawStatus": "Notice Left (No Authorized Recipient Available)",
  "rawDescription": "Notice Left (No Authorized Recipient Available)"
}

ステータスに注目してください。WhereParcelには exception というステータスも、substatusフィールドもありません。すべてのイベントは9種類の標準ステータス(pending、in_transit、out_for_delivery、delivered、failed、returned、cancelled、lost、unknown)のいずれかを持ち、配送業者の元の文言は description・rawStatus・rawDescription に残ります。配送業者が再配達する不在は in_transit のままで、詳しい事情は文言のほうにあります。

よくある配達例外には以下のものがあります。

  • 配達試行失敗 — 不在、営業時間外
  • アクセス不可 — セキュリティ付きマンション、施錠された建物
  • 受取拒否 — 受取人が荷物を拒否
  • 住所不備 — 住所が不完全または無効

通関例外

国際配送では通関に関連する保留が頻繁に発生します。

  • 書類不備 — コマーシャルインボイスや通関書類の不足
  • 検査 — 荷物が物理検査の対象に選定
  • 関税未払い — 受取人が輸入関税を支払う必要がある
  • 禁止品目 — 仕向国で制限されている内容物

輸送例外

  • 天候による遅延 — 悪天候による輸送への影響
  • 配送業者の遅延 — 仕分け施設の滞留、車両トラブル
  • 誤仕分け — 荷物が誤った施設に送られた
  • 破損 — 輸送中に荷物が損傷

WhereParcelのデータではこう見える

状況標準ステータス詳しい事情があるところ
不在で配達できず、再配達予定USPSは in_transit(配送業者によっては failed)description — 例: “Notice Left”、“Available for Pickup”
通関保留、関税未払い多くは in_transit — 通関専用のステータスはないdescription に customs・clearance・duties などの語
天候・輸送網の遅延in_transitdescription — 例: “Regional Weather Delay”
受取拒否、宛先不明faileddescription — 例: “Refused”、“Undeliverable as Addressed”
差出人へ返送returneddescription — 例: “Return to Sender”
紛失lostdescription — 例: “Sent to Mail Recovery Center”
出荷の取り消し配送業者により cancelled または faileddescription

例外処理システムの構築

ステップ1:分類と優先度付け

すべての例外に同じ対応が必要なわけではありません。以下の分類はWhereParcelが返す値ではなく、自社で決めるものです。標準ステータスと配送業者の文言から分類を作り、その上に優先度システムを構築しましょう。

const EXCEPTION_PRIORITY = {
  // Critical — requires immediate customer notification
  'damaged': 'critical',
  'lost': 'critical',
  'refused': 'critical',

  // High — customer action may be needed
  'customs_hold': 'high',
  'duties_pending': 'high',
  'incorrect_address': 'high',
  'documentation_required': 'high',
  'returned': 'high',
  'failed_delivery': 'high',

  // Medium — informational, carrier will retry
  'failed_attempt': 'medium',
  'access_issue': 'medium',
  'weather_delay': 'medium',

  // Low — temporary, usually resolves automatically
  'carrier_delay': 'low',
  'missort': 'low',
};

// item = one entry of data.trackingItems in a WhereParcel webhook
function classifyException(item) {
  const events = item.trackingData?.events ?? [];
  const latest = events[events.length - 1];                   // events are oldest first
  const text = `${latest?.description ?? ''} ${latest?.rawDescription ?? ''}`;
  const status = item.currentStatus;

  if (status === 'lost') return 'lost';
  if (/refused/i.test(text)) return 'refused';
  if (/damage/i.test(text)) return 'damaged';
  if (/undeliverable|insufficient address|no such number|vacant|moved, left no address/i.test(text)) return 'incorrect_address';
  if (/dut(y|ies)|import tax/i.test(text)) return 'duties_pending';
  if (/invoice|documentation/i.test(text)) return 'documentation_required';
  if (/customs|clearance/i.test(text)) return 'customs_hold';
  if (/no access/i.test(text)) return 'access_issue';
  if (/notice left|attempted|available for pickup|redelivery/i.test(text)) return 'failed_attempt';
  if (/weather/i.test(text)) return 'weather_delay';
  if (/missent|missort/i.test(text)) return 'missort';
  if (status === 'returned') return 'returned';
  if (status === 'failed' || status === 'cancelled') return 'failed_delivery';
  if (/delay/i.test(text)) return 'carrier_delay';
  return null;                                                // nothing unusual
}

function handleException(item, type = classifyException(item)) {
  if (!type) return;
  const priority = EXCEPTION_PRIORITY[type] || 'medium';

  switch (priority) {
    case 'critical':
      notifyCustomerImmediately(item, type);
      createSupportTicket(item, type);
      break;
    case 'high':
      notifyCustomerWithAction(item, type);
      break;
    case 'medium':
      updateTrackingPage(item, type);
      break;
    case 'low':
      logAndMonitor(item, type);
      break;
  }
}

配送業者ごとに文言は異なるため、上のパターンは出発点として使ってください。たとえばヤマト運輸は英語版サイトの文言(“Delivery failed” など)がそのまま description に入ります。分類できなかったイベントの description を記録しておき、実データからルールを増やしていきましょう。

ステップ2:お客様向けのわかりやすいメッセージ

技術的な追跡ステータスはお客様を混乱させます。明確で実行可能なメッセージに変換しましょう。

const CUSTOMER_MESSAGES = {
  'failed_attempt': {
    title: 'Delivery attempted',
    message: 'The carrier tried to deliver your package but was unable to. They will try again on the next business day.',
    action: null,
  },
  'customs_hold': {
    title: 'Package in customs',
    message: 'Your package is being processed by customs. This typically takes 1-5 business days.',
    action: null,
  },
  'duties_pending': {
    title: 'Action required: Import duties',
    message: 'Your package requires import duty payment before it can be released from customs.',
    action: {
      label: 'Pay duties',
      url: '/shipments/{trackingNumber}/duties',
    },
  },
  'incorrect_address': {
    title: 'Address issue',
    message: 'The carrier was unable to deliver due to an address issue. Please verify your shipping address.',
    action: {
      label: 'Update address',
      url: '/shipments/{trackingNumber}/address',
    },
  },
};

ステップ3:自動復旧ワークフロー

一部の例外は自動的に解決できます。

async function attemptAutoRecovery(shipment, item) {
  switch (classifyException(item)) {
    case 'failed_attempt': {
      // The webhook carries the full timeline, so count attempt scans in it
      const attempts = item.trackingData.events.filter((e) =>
        /notice left|attempted/i.test(e.description)
      );
      if (attempts.length >= 3) {
        // After 3 failed attempts, offer pickup or redirect
        await notifyCustomer(shipment, {
          message: 'Multiple delivery attempts failed',
          options: ['Schedule redelivery', 'Pick up at facility', 'Redirect to new address'],
        });
      }
      // Otherwise, carrier will retry automatically
      break;
    }

    case 'incorrect_address': {
      // Check if we have an alternative address on file
      const altAddress = await getAlternativeAddress(shipment.recipientId);
      if (altAddress) {
        await requestAddressCorrection(shipment, altAddress);
      } else {
        await requestCustomerAddressUpdate(shipment);
      }
      break;
    }
  }
}

例外率のモニタリング

例外のパターンを追跡して、組織的な問題を特定しましょう。

// Daily exception rate monitoring
async function generateExceptionReport() {
  const today = new Date();
  const shipments = await getShipmentsForDate(today);

  const report = {
    total: shipments.length,
    exceptions: {},
    carrierBreakdown: {},
  };

  for (const shipment of shipments) {
    const carrier = shipment.carrier;                  // e.g. 'jp.yamato'
    if (!report.carrierBreakdown[carrier]) {
      report.carrierBreakdown[carrier] = { total: 0, exceptions: 0 };
    }
    report.carrierBreakdown[carrier].total++;

    if (shipment.hasException) {
      const type = shipment.exceptionType;             // stored by the webhook handler below
      report.exceptions[type] = (report.exceptions[type] || 0) + 1;
      report.carrierBreakdown[carrier].exceptions++;
    }
  }

  return report;
}

アラートの設定

例外率のアラートしきい値を定義します。

例外の種類警告しきい値重大しきい値
配達失敗> 10%> 20%
通関保留> 15%(国際)> 30%(国際)
破損> 1%> 3%
紛失> 0.5%> 1%
住所不備> 5%> 10%

Webhookベースの例外処理

POST /v2/webhooks/register に recurring: true で荷物を登録すると、WhereParcelはポーリングのサイクルごと(配送業者のスキャン直後ではなく数時間おき)に再照会し、結果をエンドポイントへPOSTします。例外処理では次の2点が重要です。

  • Webhookは毎サイクル届き、毎回サブスクリプション内のすべての荷物を含みます。hasChange が true になるのは標準ステータスが変わったときだけで、in_transit のままの不在は該当しません。hasChange だけに頼らず、最後に処理したイベントを記録しておきましょう。
  • 各送信は10秒のタイムアウトで1回だけ行われ、再試行はありません。署名を検証し、すぐに2xxを返してから処理してください。
import crypto from 'node:crypto';
import express from 'express';

// Keep the raw body: X-WhereParcel-Signature is an HMAC-SHA256 (hex) of these exact bytes
app.post('/webhooks/tracking', express.raw({ type: 'application/json' }), async (req, res) => {
  const expected = crypto
    .createHmac('sha256', process.env.WHEREPARCEL_WEBHOOK_SECRET)   // your endpoint's secret
    .update(req.body)
    .digest('hex');
  const received = req.get('X-WhereParcel-Signature') ?? '';
  if (received.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))) {
    return res.status(401).end();
  }
  res.status(200).json({ received: true });

  const { data } = JSON.parse(req.body);    // event: 'tracking.registered' | 'tracking.updated'
  for (const item of data.trackingItems) {
    // 'failed' = the lookup itself failed this cycle; trackingData is the last known state
    if (item.status !== 'success' || !item.trackingData) continue;

    const events = item.trackingData.events;                // oldest first
    const latest = events[events.length - 1];
    if (!latest) continue;

    const key = `${item.carrier.code}:${item.trackingNumber}`;  // carrier is { code, name, country }
    const fingerprint = `${latest.timestamp}|${latest.description}`;
    if ((await lastHandled.get(key)) === fingerprint) continue; // already seen on a previous cycle
    await lastHandled.set(key, fingerprint);

    const type = classifyException(item);
    if (!type) continue;

    await handleException(item, type);
    await logException({                                      // Log for analytics
      trackingNumber: item.trackingNumber,
      carrier: item.carrier.code,
      status: item.currentStatus,
      exceptionType: type,
      timestamp: latest.timestamp,
    });
  }
});

ベストプラクティスまとめ

  1. 重要度別に例外を分類する — すべての例外に同じレベルの対応が必要なわけではありません
  2. お客様にわかりやすい言葉を使う — 技術的なステータスを明確なメッセージに変換しましょう
  3. 実行可能な次のステップを提示する — お客様ができることがあれば伝えましょう
  4. 可能な限り自動化する — よくある例外に対してワークフローを設定しましょう
  5. 例外率をモニタリングする — 配送業者やルートごとのパターンを追跡し、組織的な問題を早期に発見しましょう
  6. 解決までのSLAを設定する — 重大な例外は数日ではなく数時間以内に対処すべきです
  7. ポーリングではなくWebhookを使用する — 繰り返しの照会で利用枠を消費する代わりに、WhereParcelにサイクルごとの再照会と結果の送信を任せましょう

堅牢な例外処理を構築することが、フラストレーションのたまる配送体験と信頼できる配送体験を分ける鍵です。WhereParcelは39社以上の配送業者にわたって同じ9種類の標準ステータスと配送業者の原文を提供するため、分類ルールを一度作れば、どの配送業者が関わっても一貫して適用できます。

Webhookの設定について詳しくは、Webhook ベストプラクティスガイドをご覧ください。

ご希望の配送業者が見つかりませんか?リクエストいただければ迅速に対応いたします。

配送業者をリクエスト →

何か聞きたいことがあれば、気軽にどうぞ。 Discordに来てください — WhereParcelを作った開発者が直接メッセージを読んで返信します。ボットもチケットもなし。気軽に話しかけてください。

Discordに参加 → Slackに参加 →

タグ: #exceptions #error-handling #tracking #resilience #best-practices