Error handling

How the Teak Partner API reports errors, and what your server should do with each kind.

Every endpoint's page in the API reference lists the errors it returns, with an example of each. This page covers what they have in common: how to read an error, what to do with each kind, and how to retry safely.

Read an error

Check the HTTP status first. It tells you the kind of error. Then read the body for details. Its shape depends on the endpoint.

The Programs API

The Programs API returns a standard HTTP status, with a short body:

{
  "msg": "No matching policies for item 'ITEM-1'",
  "type": "Not Found"
}

msg says what's wrong, and often names the item. When the request body doesn't match the schema, it returns HTTP 422 with one entry for each field:

[
  {
    "type": "Validation Error",
    "loc": ["body", "data", "items", 0, "cost"],
    "msg": "Value error, cost must be a string. Numeric types (int, float) are not accepted."
  }
]

loc is the path to the field, so ["body", "data", "items", 0, "cost"] is the first item's cost.

Order Submit and other endpoints

Order Submit and the order, contract, and account endpoints return most errors as HTTP 400, with the specific error in error.code:

{
  "apiVersion": "2.0",
  "error": {
    "code": 404,
    "message": "invalid data. see errors for more information.",
    "errors": [
      {
        "domain": "Order",
        "reason": "NotFound",
        "message": "Session 3f1c9a2e-8b4d-4e6f-9a0b-1c2d3e4f5a6b not found"
      }
    ]
  }
}

Check the HTTP status first, and for a 400, read error.code. error.code uses HTTP status meanings, for example 404 for not found and 503 for temporarily unavailable. errors[].reason gives a machine-readable reason, and errors[].message a human-readable one.

Some errors use the real HTTP status instead: 401 for a missing or expired token, 403 when a feature isn't enabled, 422 when the body doesn't match the schema, and 409 from Order Submit when the order was already submitted.

Other formats

A few errors use a different body:

HTTP statusBodyReturned by
401The standard error, with error.code 401Any endpoint that needs an access token, when the token is missing, invalid, or expired
409{ "session_id": "...", "status": "already_submitted" }Submit an order, when the session was already submitted. Treat it as accepted.
400{ "non_field_errors": [ ... ] }Create an access token, when the keys are wrong
403{ "detail": "..." }Submit an order, when TeakOS isn't enabled for your account
422{ "detail": [ ... ] }Submit an order, when the body doesn't match the schema. Each entry's loc names the field and msg says what's wrong
404, 422{ "msg": "...", "type": "..." }Retrieve order details, when there's no order yet or primary_policy_id is invalid
400{ "msg": "...", "type": "..." }Onboard a client, when affiliate isn't in the af_... format

To handle them all in one place, turn every error into the same shape:

// Reads any Teak error response into { status, code, message }.
// status is the HTTP status. code is error.code when there is one, otherwise the HTTP status.
async function readTeakError(res) {
  const body = await res.json().catch(() => ({}));
  const fieldList = Array.isArray(body) ? body : Array.isArray(body.detail) ? body.detail : null;
  const fields = fieldList?.map((d) => `${d.loc?.join('.')}: ${d.msg}`).join('; ');
  const message =
    body.error?.errors?.map((e) => e.message).join('; ') ||
    fields ||
    (typeof body.detail === 'string' ? body.detail : '') ||
    body.msg ||
    body.status ||
    body.non_field_errors?.join('; ') ||
    res.statusText;
  return { status: res.status, code: body.error?.code ?? res.status, message };
}
def read_teak_error(res):
    """Reads any Teak error response into (status, code, message).

    status is the HTTP status. code is error.code when there is one,
    otherwise the HTTP status.
    """
    try:
        body = res.json()
    except ValueError:
        body = {}
    if isinstance(body, list):
        body = {"detail": body}
    error = body.get("error") or {}
    detail = body.get("detail")
    if isinstance(detail, list):
        detail = "; ".join(f'{".".join(map(str, d.get("loc", [])))}: {d.get("msg")}' for d in detail)
    message = (
        "; ".join(e.get("message", "") for e in error.get("errors", []))
        or detail
        or body.get("msg")
        or body.get("status")
        or "; ".join(body.get("non_field_errors", []))
        or res.reason
    )
    return res.status_code, error.get("code", res.status_code), message

Handle each kind of error

Decide what to do from the kind of error, not the individual message:

KindHow it looksWhat to doRetry?
Invalid requestHTTP 400 or 422. From Order Submit and other endpoints, a 400 carries error.code 400, 404, or 422.Fix the request. The message says what's wrong.No
No protection for an itemHTTP 404 from the Programs API, naming the item, or HTTP 422 from the Programs API for an unknown product typeThe whole call failed. Leave the item out and call again, or show it without a price. Ask your Teak integration contact to map the product type.After you change the request
Expired tokenHTTP 401Get a new access token and try again. Tokens last 5 minutes.Once
Wrong keys or accountHTTP 400 from Create an access token, HTTP 403, or error.code 403Check your keys match the environment, and that every call for a session uses the same account's keys. If a feature isn't enabled, contact your Teak integration contact.No
Already submittedHTTP 409 from Order Submit, with "status": "already_submitted". On the server path, Teak tells you the order was already placed.An earlier attempt already placed the order. Treat it as success, not as a failure.No
Not created yetHTTP 404 from Retrieve order details just after Order Submit returned 202Teak creates the order a few seconds after Order Submit. Wait and try again, or call it from your Contract Issued handler.Yes, after a few seconds
Temporarily unavailableHTTP 503, or error.code 503Retry with backoff, for example after 1, 5, and 30 seconds. From Order Submit, it can also mean an earlier request for the session is still being processed. If it continues, check status.helloteak.com.Yes
No responseA timeout or network errorYou don't know whether the request went through. Retry it: see Retry safely.Yes

Retry safely

  • Order Submit is safe to retry with the same session ID. The session identifies the order, so a retry can't create a second one. If an earlier attempt went through, the retry returns HTTP 409 with "status": "already_submitted": the order is submitted. If an earlier attempt is still being processed, the retry returns error.code 503: wait and retry. Send the same body each time. Teak keeps the first submitted order.
  • The Programs API is safe to retry with the same session_id, and returns the same protection. If your first call, the one without a session_id, gets no response, call again without one. Teak starts a new session, and the lost one is never used. See Sessions.
  • Confirming the order on the server path is safe to retry on the same session: Teak never creates a second order for a session. See Confirm the order.
  • Keep reference_id unique across all your orders, and reuse it only when you retry the same session. A new session with an order number that's already used is rejected.
  • Retrieving an order (details or links) changes nothing, so it's always safe to retry.
  • Voiding or canceling a contract twice doesn't change it twice. If a retry says the contract is already voided or canceled, the first attempt went through.
  • Access tokens last 5 minutes. If a retry returns 401, get a new token and retry once.

For Order Submit, the Submit an order reliably recipe puts all of this in one function, in Node.js and Python.

Keep the customer's order safe

Call Teak's Order Submit endpoint only after your own order is confirmed, and never fail or undo the customer's purchase because of a Teak error. Their payment has already gone through. Log the error, retry where the table above says to, and alert your team if it keeps failing. The checkout example submits in the background, so checkout never waits on Teak.

When you contact Teak

Send your Teak integration contact:

  • The endpoint and the time of the request, with its time zone
  • The environment: sandbox or production
  • The HTTP status and the full response body
  • The IDs involved: the session ID, your reference_id, or the policy_number

Never send your secret key or an access token.

Next steps

To see each endpoint's errors, or put this into practice:


Did this page help you?