# Errors

Every error code, what caused it and what to do next.

A failed request answers with a Problem. The SDKs throw it as `CommerceError`:

```ts
try {
  await cart.add("BACKPACK-30-GREEN");
} catch (error) {
  if (error instanceof CommerceError) {
    error.problem.code; // what happened
    error.problem.kind; // the category
    error.problem.retryable; // may the same request succeed later?
    error.problem.cart; // the Cart as it is, when the buyer can fix it
  }
}
```

On the wire, a Problem is RFC 9457 Problem Details, the same in every OrbCommerce
product:

```json
{
  "title": "Bad Request",
  "status": 400,
  "code": "body_invalid",
  "kind": "invalid",
  "retryable": false,
  "requestId": "req_01J8Z3W6Q4XB7N2M5K9RTV0HCE",
  "detail": "The request body violates the schema of this operation; errors names each field.",
  "errors": [{ "pointer": "#/body/email", "code": "invalid_format", "detail": "Invalid email." }]
}
```

`title` is the HTTP status phrase. Each entry of `errors` points into the request:
`#/body/...` at a field of the body, `#/query/...` at a query parameter. A Problem
may carry members of its own, such as `cart`; ignore the ones you don't know. Every
`401` names its scheme in `WWW-Authenticate`.

**Not errors:** a declined payment, `quote_changed` and `pending` are normal results
of `pay()` and `accept()`. [Outcomes →](/docs/shop/quotes#4-place-the-order)

## Decide by kind

When you meet a code you don't handle, `kind` tells you the general next step:

| `kind`         | Next step                                                        |
| -------------- | ---------------------------------------------------------------- |
| `invalid`      | Fix the input. Show the buyer what to correct.                   |
| `unauthorized` | The credential is missing or wrong. A bug in your setup.         |
| `forbidden`    | The credential is valid but not allowed here.                    |
| `not_found`    | The Cart, Quote or Order doesn't exist for this credential.      |
| `conflict`     | The state moved on. Read the Cart again and continue from there. |
| `rate_limited` | Wait and repeat with the same `Idempotency-Key`.                 |
| `unavailable`  | A system is temporarily away. Repeat later with the same key.    |
| `internal`     | Our bug. Report the `requestId`.                                 |

## The buyer can fix it

Show a friendly message. `describe(locale).problem(code)` has one in four languages.

| Code                          | Cause                                           | What to do                                          |
| ----------------------------- | ----------------------------------------------- | --------------------------------------------------- |
| `cart_incomplete`             | Details missing for a Quote.                    | Ask for `problem.missing`.                          |
| `ship_to_invalid`             | The address fails the country's rules.          | Highlight `problem.invalid`, such as `postalCode`.  |
| `bill_to_invalid`             | Same, for the billing address.                  | Highlight `problem.invalid`.                        |
| `ship_to_incomplete`          | A partial address where a full one is needed.   | Ask for the full address.                           |
| `ship_to_unsupported`         | You don't ship to this country.                 | Let the buyer choose another country.               |
| `shipping_method_unavailable` | The chosen method isn't offered here.           | Show `cart.shippingMethods` again.                  |
| `not_shippable`               | Some Lines can't go to this address.            | Offer to remove `problem.lines`.                    |
| `lines_unavailable`           | Lines can no longer be bought.                  | Offer to remove `problem.lines`.                    |
| `code_invalid`                | The code applies to nothing in this Cart.       | Say so at the code field.                           |
| `quantity_invalid`            | Not a positive whole number.                    | Correct the quantity field.                         |
| `configuration_invalid`       | A line extension value was refused.             | Map `problem.errors[].pointer` to your fields.      |
| `extension_invalid`           | A Cart extension value was refused.             | Map `errors`, or fix the names in `invalid`.        |
| `payment_method_unavailable`  | The method doesn't fit this buyer.              | Offer `quote.paymentMethods`.                       |
| `tax_undeterminable`          | No tax for `problem.country` and `taxCategory`. | Your tax setup. Let the buyer pick another address. |

## The purchase moved on

| Code                                             | Cause                                                   | What to do                                                              |
| ------------------------------------------------ | ------------------------------------------------------- | ----------------------------------------------------------------------- |
| `cart_locked`                                    | A payment for this Cart is running.                     | Reopen its Quote with `openQuote()` or `resume()`. Don't start another. |
| `cart_ordered`                                   | The Cart already became an Order.                       | `commerce.continueShopping(token)`.                                     |
| `cart_not_ordered`                               | `continueShopping` before the purchase was handed over. | Keep using the current Cart.                                            |
| `cart_merged`                                    | The buyer signed in and this Cart joined theirs.        | Continue with the Cart from `identify()`.                               |
| `quote_not_current`                              | The Cart changed after this Quote.                      | Ask for a new Quote.                                                    |
| `preparation_unavailable`, `preparation_unknown` | A PayPal approval expired or doesn't match.             | Start the express step again.                                           |
| `payment_instrument_required`                    | An agent or server accepted without a token.            | Pass `instrument` to `accept()`.                                        |

## Not found

`cart_not_found`, `line_not_found`, `quote_not_found`, `order_not_found`,
`payment_not_found`, `component_not_found`, `event_not_found`, `receiver_not_found`,
`withdrawal_not_found`, `route_not_found`.

A `cart_not_found` on a saved token usually means the Cart expired after 180 days
without activity, or it belongs to a signed-in buyer whose token is missing. Start
a new Cart quietly.

## Setup and credentials

Fix these in your code or configuration. Buyers should never see them.

| Code                     | Cause                                                                                                                                     |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `unauthorized`           | No `Authorization` header, or an unknown key or token; `detail` says which.                                                               |
| `environment_mismatch`   | A `test` key against `live`, or the other way round.                                                                                      |
| `not_permitted`          | The credential may not do this, such as a publishable key on an Admin route; for staff, `area` and `level` say what to ask the owner for. |
| `not_a_member`           | A staff token of someone the owner removed from the staff.                                                                                |
| `origin_not_allowed`     | The browser's origin isn't in the Channel's `origins`.                                                                                    |
| `buyer_token_invalid`    | The `OrbCart-Buyer` token is expired or from an unknown issuer.                                                                           |
| `buyer_token_missing`    | `identify()` without a signed-in buyer.                                                                                                   |
| `buyer_token_unexpected` | A buyer token next to a secret key.                                                                                                       |

## Request format

| Code                       | Cause                                                                                 |
| -------------------------- | ------------------------------------------------------------------------------------- |
| `body_invalid`             | The body isn't JSON, is over 1 MB, or doesn't match the schema. See `problem.errors`. |
| `parameter_invalid`        | A query parameter doesn't match the schema, such as an unknown `after`. See `errors`. |
| `idempotency_key_required` | This operation needs an `Idempotency-Key`.                                            |
| `idempotency_key_invalid`  | The key is malformed.                                                                 |
| `idempotency_key_reused`   | The same key with a different body. Use a new key.                                    |
| `request_in_progress`      | The first request with this key is still running. Repeat shortly.                     |

## Temporarily unavailable

Repeat the same request with the same key, after the pause `Retry-After` names.
Check `retryable` on the Problem to be sure.

`unavailable`, `provider_unavailable`, `identity_unavailable`,
`invalidation_pending`, `internal`. Not `projection_unavailable`: an environment
without an order list stays without one, so open orders by ID or number instead.

`rate_limited` answers `POST /v1/withdrawals` past 5 declarations per email or 20
per client network in a minute. Tell the shopper to try again in a minute; a
declaration received before stays received. It answers `POST /v1/gift-cards/lookup` and a
desk redemption past 10 codes per client network in any minute.

## Refunds and fulfillment

| Code                        | Cause                                                    |
| --------------------------- | -------------------------------------------------------- |
| `refund_exceeds_order`      | More units than the Order has left.                      |
| `refund_exceeds_captured`   | More money than was captured.                            |
| `nothing_to_refund`         | The selection adds up to zero.                           |
| `refund_changed`            | The amount differs from `expectedAmount`. Preview again. |
| `fulfillment_exceeds_order` | More units shipped than ordered.                         |
| `withdrawal_settled`        | The withdrawal is already on an Order or handled.        |

## Webhooks

`provider_webhook_invalid`, `provider_webhook_signature_invalid` and
`provider_webhook_unavailable` go to the payment provider, not to you. A
signature error almost always means a wrong webhook secret, or two Adyen webhooks
on the same URL.

## Support

Every Problem has a `requestId`. Log it, never the request body. It finds the
request from the admin's Orders area without exposing personal data.