> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cubestack.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Handle Errors

> Learn how to properly handle API errors in your application.

# Handle Errors

Proper error handling ensures a smooth experience for your users.

## Check Status Codes

Always check the HTTP status code before processing the response:

```javascript theme={null}
const response = await fetch(url, { headers });

if (!response.ok) {
  const { error } = await response.json();

  switch (response.status) {
    case 400:
      console.error('Bad request:', error);
      break;
    case 401:
      console.error('Unauthorized — check your API key');
      break;
    case 404:
      console.error('Resource not found');
      break;
    case 429:
      console.error('Rate limited — slow down');
      break;
    default:
      console.error('Unexpected error:', error);
  }
  return;
}

const data = await response.json();
```

## Retry on Transient Errors

For `429` (rate limited) and `5xx` (server errors), implement retry with exponential backoff:

```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const response = await fetch(url, options);

    if (response.ok) return response.json();
    if (response.status === 429 || response.status >= 500) {
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
      continue;
    }

    throw new Error(`API error: ${response.status}`);
  }
  throw new Error('Max retries exceeded');
}
```

## Validate Before Sending

Reduce errors by validating data before making API calls:

* Check required fields are present
* Validate data types match your cube schema
* Ensure values are within allowed ranges

See [Error Codes](/reference/error-codes) for the full list.
