Handle errors and retries
Decide which errors to retry, back off safely, refresh tokens, and never book a shipment twice.
- Product
- APIShipping Engine API
- Section
- Guides
- Reading time
- 7 min read
Goal: make your integration recover by itself from temporary failures, stop quickly on errors that need a fix, and never create a duplicate booking.
Before you start: you have a working integration that requests rates and creates orders. See Book a shipment. The error format is described in Errors.
Read the error
Every error has the same shape.
messageis a string, or a list of strings for validation errors:{ "statusCode": 400, "message": "Shipping rate code 'SR-7KQ2M9XA' have expired.", "error": "Bad Request" }A few errors add a machine-readable
code, for examplePICKUP_SCHEDULE_EXPIREDandPICKUP_SCHEDULE_NOT_QUOTED. Branch onstatusCodeandcodewhen present; usemessagefor logs and for matching known cases.With cURL, print the status code next to the body:
curl -s -o response.json -w "%{http_code}\n" "$FASTRAC_API/b2b/user-balance" \ -H "Authorization: Bearer $FASTRAC_TOKEN" cat response.jsonDecide whether to retry
Status Meaning Retry? 400The request is invalid or not possible as sent. No. Fix the request. For Payment failed, but order … was created, re-quote and create a new order (details).401Token missing, expired or invalid. Once, after getting a new token. 403Your API key lacks a permission, or the resource belongs to another account. No. Ask your account admin. 404Not found. For rates: no courier serves the route. No. 422Valid request, wrong state (for example an invalid date filter). No. 429Too many requests. Yes, with backoff. 500,502,503,504Temporary server or courier problem. Yes, with backoff, if the operation is safe to repeat (next step). No response (timeout, connection reset) You don't know whether it worked. Same as 5xx.Know which operations are safe to repeat
Operation Safe to repeat? Why Every GETYes Reads only. POST /b2b/shipping-rateYes Each call creates a fresh quote. Unused quotes just expire. POST /b2b/shipments/cancel/{code},POST /b2b/orders/{code}/cancelYes Cancelling an already cancelled shipment returns success. POST /b2b/webhook/setWebhookYes It replaces your single endpoint. POST /b2b/ordersNo It has no idempotency key. Repeating it can book and charge twice. See order timeouts. Back off between attempts
Wait longer after each failure, add random jitter so many clients don't retry together, and give up after a few attempts:
retry.js const RETRYABLE = new Set([429, 500, 502, 503, 504]); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); async function withRetry(fn, { attempts = 5, baseMs = 1000, maxMs = 30_000 } = {}) { for (let i = 1; ; i++) { let res; try { res = await fn(); if (!RETRYABLE.has(res.status)) return res; // success, or an error retrying won't fix } catch (err) { if (i >= attempts) throw err; // network error or timeout } if (i >= attempts) return res; const delay = Math.min(maxMs, baseMs * 2 ** (i - 1)); await sleep(delay / 2 + Math.random() * (delay / 2)); // 0.5–1 s, 1–2 s, 2–4 s, 4–8 s } } // Only for operations that are safe to repeat: const res = await withRetry(() => api('GET', '/b2b/shipments?status=IN_TRANSIT'));Refresh the token on 401
Access tokens are short-lived (
expires_in, in seconds). Cache the token, renew it shortly before it expires, and on a401renew it once and repeat the request once:api.js let cached = { token: null, expiresAt: 0 }; async function getToken(force = false) { if (!force && cached.token && Date.now() < cached.expiresAt - 30_000) return cached.token; const res = await fetch(process.env.FASTRAC_TOKEN_URL, { method: 'POST', body: new URLSearchParams({ grant_type: 'client_credentials', client_id: process.env.FASTRAC_CLIENT_ID, client_secret: process.env.FASTRAC_CLIENT_SECRET, }), }); if (!res.ok) throw new Error(`Token request failed: ${res.status}`); // wrong or rotated secret const { access_token, expires_in } = await res.json(); cached = { token: access_token, expiresAt: Date.now() + expires_in * 1000 }; return cached.token; } async function api(method, path, body) { const call = async (token) => fetch(`${process.env.FASTRAC_API}${path}`, { method, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: body && JSON.stringify(body), signal: AbortSignal.timeout(60_000), // booking can take several seconds }); let res = await call(await getToken()); if (res.status === 401) res = await call(await getToken(true)); // one retry with a new token return res; }If the second attempt is still
401, stop: the key was probably rotated or the secret is wrong. Messages you may see:Missing authorization header,Invalid authorization scheme, or an expired or invalid token. See Authentication.
After an order request times out
POST /b2b/orders books the courier before it answers, so it can take several seconds. Give it a
generous client timeout (for example 60 seconds). If you still get no answer, or a 5xx, the order
may or may not exist. Check before you try again:
- Wait about a minute.
- Search for the shipment by its receiver, created since just before your request:
curl -s -G "$FASTRAC_API/b2b/shipments" \
-H "Authorization: Bearer $FASTRAC_TOKEN" \
--data-urlencode "search=081298765432" \
--data-urlencode "startDate=2026-11-20T10:25:00+07:00"- If a matching shipment is listed, the booking went through: store its codes and don't book again.
- If nothing is listed, no shipment was booked (failed orders are not listed). Re-quote if the rate has expired, then create the order again.
You can also check your balance logs for a
Payment for order … debit in that window.
Handle validation errors
When fields are missing or have the wrong type, you get 400 with one message per problem. Each starts with the path of the field:
{
"statusCode": 400,
"message": [
"shipments.0.receivers.0.phoneNumber should not be empty",
"shipments.0.shippingOptions.fulfillmentMethod must be one of the following values: PICKUP, DROPOFF"
],
"error": "Bad Request"
}function fieldErrors(body) {
const messages = Array.isArray(body.message) ? body.message : [body.message];
return messages.map((m) => {
const [path, ...rest] = m.split(' ');
return /^[\w.]+$/.test(path) && rest.length ? { field: path, error: rest.join(' ') } : { field: null, error: m };
});
}
// → [{ field: 'shipments.0.receivers.0.phoneNumber', error: 'should not be empty' }, …]Show the field errors to whoever entered the data, fix them, and send again. Never retry unchanged.
Unknown fields are ignored, not rejected
Fields the API doesn't know are dropped silently. A typo such as fulfilmentMethod doesn't cause an
error: the default is used instead. Compare the response with what you meant to send. Request bodies
are limited to 1 MB.
Log enough for support
When you contact support, the request time and the codes involved let us find your case quickly. For every API call that fails, log:
| Log | Example |
|---|---|
| Time, with offset | 2026-11-20T10:25:13+07:00 |
| Method and path | POST /b2b/orders |
| Status and full response body | 400, {"message": "…"} |
| Codes involved | SR-7KQ2M9XA, FSO-261120-A1B2C3, SHP-261120-D4E5F6, airway bill |
| Your own reference | Your order or cart ID |
| Environment | Sandbox or production, and your client_id |
Never log secrets
Don't log the client_secret, access tokens, or webhook secrets. Mask the Authorization header.
Checklist
- Retry only
429,5xxand network errors, and only for operations that are safe to repeat. - Back off exponentially with jitter; stop after about 5 attempts.
- Cache tokens; on
401, renew once and retry once. - After a timeout on
POST /b2b/orders, search for the shipment before booking again. - Map validation messages to fields; never resend an unchanged invalid request.
- Log time, path, status, body and codes, without secrets.
Was this page helpful?