배송 추적 예외 처리: 개발자를 위한 엣지 케이스 가이드
배송 실패, 통관 보류, 주소 오류 등 다양한 택배조회 예외 상황을 처리하는 방법을 알아보세요. 안정적인 배송 연동 시스템을 구축하기 위한 실용적인 패턴을 소개합니다.
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_transit | description — 예: “Regional Weather Delay” |
| 수취 거부, 주소 불명 | failed | description — 예: “Refused”, “Undeliverable as Addressed” |
| 발송인에게 반송 | returned | description — 예: “Return to Sender” |
| 분실 | lost | description — 예: “Sent to Mail Recovery Center” |
| 발송 취소 | 택배사에 따라 cancelled 또는 failed | description |
예외 처리 시스템 구축
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;
}
}
택배사마다 문구가 다르므로 위 패턴은 출발점으로만 쓰세요. 한국 택배사는 원문이 한국어이니 ‘미배달’·‘반송’·‘통관’ 같은 단어를 함께 넣고, 분류하지 못한 이벤트의 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. 'kr.cj'
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 합니다. 예외 처리에서는 두 가지가 중요합니다:
- 웹훅은 매 주기 오고, 매번 구독에 들어 있는 모든 송장을 담습니다.
hasChange는 표준 상태가 바뀌었을 때만true입니다 —in_transit그대로인 부재 건은 바꾸지 않습니다. 그러니hasChange에만 기대지 말고 마지막으로 처리한 이벤트를 기억해 두세요. - 각 전송은 10초 제한으로 한 번만 시도되고 재시도하지 않습니다. 서명을 확인하고 곧바로 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,
});
}
});
모범 사례 정리
- 예외를 심각도별로 분류 — 모든 예외에 동일한 수준으로 대응할 필요는 없습니다
- 고객 친화적 언어 사용 — 기술적 상태를 명확한 메시지로 변환하세요
- 구체적인 다음 단계 제시 — 고객이 취할 수 있는 조치가 있다면 안내하세요
- 가능한 부분은 자동화 — 자주 발생하는 예외에 대한 워크플로우를 설정하세요
- 예외 발생률 모니터링 — 택배사별, 경로별 패턴을 추적하여 시스템적 문제를 조기에 파악하세요
- 해결 SLA 설정 — 심각한 예외는 며칠이 아닌 몇 시간 내에 처리해야 합니다
- 폴링 대신 webhook 사용 — 반복 조회로 사용량을 쓰는 대신, WhereParcel 이 주기마다 모든 송장을 다시 조회해 결과를 보내 주게 하세요
견고한 예외 처리 시스템은 불편한 배송 경험과 신뢰할 수 있는 배송 경험을 가르는 핵심 요소입니다. WhereParcel 은 39개 이상의 택배사에 걸쳐 같은 표준 상태 9가지와 택배사 원문을 함께 제공하므로, 분류 규칙을 한 번만 만들면 어떤 택배사를 사용하든 일관되게 적용할 수 있습니다.
Webhook 설정에 대한 자세한 내용은 Webhook 모범 사례 가이드를 참고하세요.
원하는 택배사가 없으신가요? 요청해 주시면 빠르게 연동해 드립니다.
택배사 요청하기 →더 알아보기
궁금한 게 있으세요? 편하게 물어보세요. Discord에 들어오시면 WhereParcel을 만든 개발자가 직접 읽고 답장드립니다. 봇도 없고 티켓도 없어요. 그냥 편하게 대화하세요.
Discord 참여하기 → Slack 참여하기 →