# Errors (/docs/basic-concepts/error-handling)

When a call fails, the API answers with an HTTP status code and the same error object every time. This page shows how to read that object and what to do for each status, so your code can tell a typo from a declined card.

## The error object [#the-error-object]

```json
{
  "error": {
    "type": "not_found",
    "code": "resource_not_found",
    "message": "Product not found: widget-pro does not exist.",
    "reference": "qh81SPw",
    "status": 404,
    "meta": null
  }
}
```

| Field | What it holds |
| --- | --- |
| `type` | The broad category. It always matches `status`, for example `not_found` for `404`. |
| `code` | The exact error within its type, for example `invalid_input` or `payment_declined`. New codes may be added, so always keep a fallback for each status. |
| `message` | What went wrong and often how to fix it, written for a person and in the shopper's language where a translation exists. Show it, but do not parse it: the wording can change. |
| `reference` | A short code that names the exact check that refused the request. The same check always gives the same reference, so it is not unique to your call. Quote it when you contact support. |
| `status` | The HTTP status code of the response. |
| `meta` | More detail when there is any, such as the failed payment after a decline. Usually `null`. |

Branch on `status` and `code`. Never branch on `message`.

## Status codes [#status-codes]

Codes in the `2xx` range mean success. Everything else is an error with the object above.

| Status | Type | What it means | What to do |
| --- | --- | --- | --- |
| `200` | | The call worked. | |
| `201` | | An object was created. It is in the body. | |
| `204` | | The call worked and there is no body, usually after a delete. | |
| `400` | `bad_request` | The request is wrong: a missing or invalid field or query parameter (`invalid_input`), JSON that does not parse (`invalid_syntax`), a promotion code that does not apply (`invalid_promotion_code`). | Fix the request. The message names the field. Sending it again unchanged gets the same answer. |
| `401` | `unauthorized` | The token is missing, expired or not valid (`invalid_token`). | Get a new token. A shopper's browser asks for a new limited token; a staff tool signs the user in again. |
| `402` | `transaction_error` | The payment gateway refused a payment, refund, capture or void (`payment_declined`, `invalid_cvv`, `invalid_avs`, `transaction_failure`). | Show the message and let the shopper try another card or method. Do not retry on your own. |
| `403` | `forbidden` | The token is valid but may not do this (`insufficient_permissions`), the browser's origin is not allowed (`invalid_origin`), or the call used `http://` (`tls_required`). | Give the token the permission, use another token type, add the origin, or use `https://`. |
| `404` | `not_found` | The object does not exist (`resource_not_found`). An object of the other mode, such as a live order read with a test token, is usually not found either. | Check the id and that the token's mode matches the object. |
| `409` | `conflict` | The request clashes with something: a value already in use (`in_use`), an exact repeat of a payment that just succeeded (`duplicate`), a feature not turned on (`feature_not_enabled`), or another payment on the same cart or invoice that is still running or could not be confirmed (`payment_in_progress`, `payment_unconfirmed`). | For a payment, do not pay again. Read the cart's or invoice's payments first (see below). |
| `422` | `unprocessable` | The request is valid but cannot be done now, for example a refund on a payment already refunded (`invalid_state`) or an account limit (`account_limit_exceeded`). | Read the object to see its state. The message says why. |
| `429` | `too_many_requests` | Too many calls in a short time (`request_limit_exceeded`). | Wait, then slow down. Never resend a payment because of a `429`; read its state instead. |
| `500` | `internal_server_error` | Something failed inside Comecero (`unspecified_error`). | A read can be tried again later. For anything that writes, read the object first to see if it changed. If it keeps happening, contact support with the `reference`. |
| `502` | `external_server_error` | The payment gateway or another outside service answered with an error (`bank_network_error`, `remote_server_error`). The payment, when there is one, is in `error.meta.payment`. | Show the shopper a message. Do not retry the payment on your own. |
| `504` | `external_server_timeout` | The payment gateway or another outside service did not answer in time (`bank_network_timeout`, `remote_server_timeout`). | The payment may have gone through. Read it before you do anything else. |

## Payment errors [#payment-errors]

Calls that take money ([Pay for a cart](/api/carts/create-cart-payment), [Pay an invoice](/api/invoices/create-invoice-payment), [Create a payment](/api/payments/create-payment)) can fail in ways other calls cannot.

<Callout type="warn">
Never retry a payment automatically. Not after a `402`, a `409`, a `429`, a `5xx` or a network error. A payment that looks failed may have charged the card, and a second try can charge the shopper twice. Only the shopper should start a new payment, after your page has shown them what happened.
</Callout>

A declined payment answers `402`. This is the answer from [Pay for a cart](/api/carts/create-cart-payment); the failed payment (trimmed here) is in `error.meta.payment`, so you can show the reason and keep a record of it.

```json
{
  "error": {
    "type": "transaction_error",
    "code": "payment_declined",
    "message": "The payment was declined or could not be processed. Please try another payment method, or contact your bank for assistance and try again.",
    "reference": "YrpsaAx",
    "status": 402,
    "meta": {
      "payment": {
        "object": "payment",
        "payment_id": "0142130709984PyZwyr0YD",
        "status": "failed",
        "success": false
      }
    }
  }
}
```

In test mode, the card `4444555566669999` always declines, so you can try this response. The full list of test cards is in [Create an account](/docs/getting-started/create-an-account).

When you get a `504`, a `500` or no answer at all, find out what happened before you show anything:

1. List the payments for the cart with [List cart payments](/api/carts/list-cart-payments), or for the invoice with [List invoice payments](/api/invoices/list-invoice-payments).
2. If one is `completed` or `pending`, the shopper has paid. Show the receipt and do not take another payment.
3. If the last one is `failed`, show the error and let the shopper choose to try again.

A `409` with code `payment_in_progress` or `payment_unconfirmed` means Comecero stopped a second payment to protect the shopper. Show the message and check the payments in the same way.

## Handle errors in code [#handle-errors-in-code]

```js
async function comecero(path, options = {}) {
  const response = await fetch(`https://api.comecero.com/api/v1${path}`, {
    ...options,
    headers: {
      Authorization: `Bearer ${process.env.COMECERO_TEST_TOKEN}`,
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  if (response.status === 204) return null;
  const body = await response.json();
  if (response.ok) return body;

  const { status, code, message, reference } = body.error;
  const error = new Error(message);
  Object.assign(error, { status, code, reference });
  throw error;
}

try {
  await comecero('/products/widget-pro');
} catch (error) {
  if (error.status === 404) {
    // The product does not exist in this mode.
  } else if (error.status === 401) {
    // Get a new token.
  } else {
    console.error(`${error.status} ${error.code} (${error.reference}): ${error.message}`);
  }
}
```

Each endpoint page in the [API reference](/api) lists the status codes that endpoint can return.

## Next steps [#next-steps]

<Cards>
  <Card title="Authentication" href="/docs/basic-concepts/authentication" />
  <Card title="Lists and pagination" href="/docs/basic-concepts/lists-and-pagination" />
</Cards>
