whereparcel

Stuck on integration? Have a question? The developer is standing by.

Guide 9 min read

Handling Tracking Exceptions: A Developer's Guide to Edge Cases

Learn how to handle delivery failures, customs holds, address issues, and other package tracking exceptions in your shipping integration. Practical patterns for building resilient applications.

WhereParcel Team

In a perfect world, every package would move smoothly from pickup to delivery. In reality, 5-15% of shipments encounter exceptions — failed deliveries, customs holds, damaged packages, or address problems. How your application handles these exceptions determines whether customers trust your shipping experience or flood your support channels.

Common Tracking Exception Types

Understanding exception categories helps you build appropriate handling for each:

Delivery Exceptions

Here is how a missed USPS delivery looks as the latest entry in data.events (events are oldest first, so the latest one is the last element):

{
  "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)"
}

Notice the status. WhereParcel has no exception status and no substatus field. Every event carries one of nine standardized statuses — pending, in_transit, out_for_delivery, delivered, failed, returned, cancelled, lost, unknown — and the carrier’s own wording stays in description, rawStatus and rawDescription. A missed attempt the carrier will retry is still in_transit; the detail is in the text.

Common delivery exceptions include:

  • Failed attempt — Nobody home, business closed
  • Access issue — Gated community, locked building
  • Refused — Recipient refused the package
  • Incorrect address — Address incomplete or invalid

Customs Exceptions

International shipments frequently encounter customs-related holds:

  • Documentation required — Missing commercial invoice or customs forms
  • Inspection — Package selected for physical inspection
  • Duties pending — Recipient needs to pay import duties
  • Prohibited item — Contents restricted in destination country

Transit Exceptions

  • Weather delay — Severe weather affecting transportation
  • Carrier delay — Sorting facility backlog, vehicle issues
  • Missort — Package routed to wrong facility
  • Damaged — Package damaged during transit

How These Show Up in WhereParcel Data

SituationStandardized statusWhere the detail is
Missed attempt, carrier will retryin_transit for USPS (some carriers report it as failed)description, e.g. “Notice Left”, “Available for Pickup”
Customs hold, duties dueUsually in_transit — there is no customs statusdescription mentions customs, clearance or duties
Weather or network delayin_transitdescription, e.g. “Regional Weather Delay”
Refused, undeliverable addressfaileddescription, e.g. “Refused”, “Undeliverable as Addressed”
Sent back to the shipperreturneddescription, e.g. “Return to Sender”
Lost in the networklostdescription, e.g. “Sent to Mail Recovery Center”
Shipment voidedcancelled or failed, depending on the carrierdescription

Building an Exception Handling System

Step 1: Categorize and Prioritize

Not all exceptions require the same response. The categories below are yours, not WhereParcel’s — derive them from the standardized status plus the carrier’s wording, then build a priority system on top:

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;
  }
}

Carrier wording varies, so treat these patterns as a starting point: log the description of every event you could not classify and extend the rules from real data.

Step 2: Customer-Friendly Messaging

Technical tracking statuses confuse customers. Map them to clear, actionable messages:

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',
    },
  },
};

Step 3: Automated Recovery Workflows

Some exceptions can be resolved automatically:

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;
    }
  }
}

Monitoring Exception Rates

Track exception patterns to identify systemic issues:

// 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. 'us.usps'
    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;
}

Setting Up Alerts

Define thresholds for exception rate alerts:

Exception TypeWarning ThresholdCritical Threshold
Failed delivery> 10%> 20%
Customs hold> 15% (intl.)> 30% (intl.)
Damaged> 1%> 3%
Lost> 0.5%> 1%
Address issue> 5%> 10%

Webhook-Based Exception Processing

Register your shipments with POST /v2/webhooks/register and recurring: true, and WhereParcel re-checks them on every polling cycle (every several hours, not the instant a carrier scans) and POSTs the result to your endpoint. Two details matter for exception handling:

  • A webhook arrives on every cycle, and each one lists every parcel in the subscription. hasChange is true only when the standardized status moved — a missed attempt that stays in_transit does not flip it. Remember the last event you handled instead of relying on hasChange alone.
  • Each delivery is attempted once with a 10-second timeout and is not retried. Verify the signature, answer 2xx at once, then do the work.
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,
    });
  }
});

Best Practices Summary

  1. Categorize exceptions by severity — Not all exceptions need the same response level
  2. Use customer-friendly language — Translate technical statuses into clear messages
  3. Provide actionable next steps — Tell customers what they can do, if anything
  4. Automate where possible — Set up workflows for common exceptions
  5. Monitor exception rates — Track patterns by carrier and route to catch systemic issues early
  6. Set SLAs for resolution — Critical exceptions should be addressed within hours, not days
  7. Use webhooks, not polling — Let WhereParcel re-check every parcel on each cycle and push the result, instead of spending your quota on repeated lookups

Building robust exception handling is what separates a frustrating shipping experience from a trustworthy one. WhereParcel gives you the same nine standardized statuses and the carrier’s original wording across 39+ live carriers, so you can build this classification once and apply it consistently regardless of which carrier is involved.

For more on webhook setup, see our Webhook Best Practices guide.

Can't find your carrier? We add new carriers on request — just let us know.

Request a carrier →

Got a question? Just ask. Drop by our Discord — the developer behind WhereParcel reads every message and replies personally. No bots, no tickets, just a real conversation.

Join Discord → Join Slack →

Tags: #exceptions #error-handling #tracking #resilience #best-practices