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

# Errors

> Error codes and how to handle them

The Safefy API uses conventional HTTP response codes to indicate the success or failure of requests.

## Response format

**Success:**

```json theme={null}
{
  "data": { ... },
  "message": "Operation completed successfully."
}
```

**Error:**

```json theme={null}
{
  "data": null,
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Insufficient balance to complete this cashout."
  }
}
```

***

## HTTP status codes

| Code  | Meaning                                                |
| ----- | ------------------------------------------------------ |
| `200` | Success                                                |
| `201` | Resource created                                       |
| `400` | Validation error or business rule violation            |
| `401` | Not authenticated  missing or invalid token            |
| `403` | Unauthorized  valid token but insufficient permissions |
| `404` | Resource not found                                     |
| `409` | Conflict  duplicate `externalId`                       |
| `429` | Rate limit exceeded                                    |
| `500` | Internal server error                                  |

***

## Error codes

| Code                      | HTTP | Description                                  |
| ------------------------- | ---- | -------------------------------------------- |
| `VALIDATION_ERROR`        | 400  | One or more request fields are invalid       |
| `AUTHENTICATION_REQUIRED` | 401  | No authentication token provided             |
| `INVALID_TOKEN`           | 401  | Token is invalid or expired                  |
| `FORBIDDEN`               | 403  | Insufficient permissions for this action     |
| `NOT_FOUND`               | 404  | Requested resource does not exist            |
| `DUPLICATE_EXTERNAL_ID`   | 409  | The `externalId` is already in use           |
| `INSUFFICIENT_BALANCE`    | 400  | Not enough balance available for the cashout |
| `RATE_LIMIT_EXCEEDED`     | 429  | Too many requests  slow down and retry       |
| `INTERNAL_ERROR`          | 500  | Unexpected server error                      |

***

## Handling errors

```javascript theme={null}
try {
  const response = await fetch('https://api-payment.safefypay.com.br/v1/cashouts', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ amount: 5000, pixKeyType: 'CPF', pixKey: '12345678901' }),
  });

  const data = await response.json();

  if (!response.ok) {
    switch (data.error?.code) {
      case 'INSUFFICIENT_BALANCE':
        console.error('Insufficient balance for this cashout.');
        break;
      case 'RATE_LIMIT_EXCEEDED':
        console.error('Rate limit hit. Try again later.');
        break;
      case 'VALIDATION_ERROR':
        console.error('Invalid request:', data.error.message);
        break;
      default:
        console.error('API error:', data.error?.message);
    }
    return;
  }

  console.log('Cashout created:', data.data);
} catch (err) {
  console.error('Network error:', err);
}
```

***

## Rate limiting

When you exceed the allowed request rate, the API returns `429 Too Many Requests` with a `Retry-After` header indicating how many seconds to wait before retrying.

<Tip>
  Always read the `Retry-After` header and wait the specified duration before retrying. Ignoring this header and retrying immediately will continue to return `429`.
</Tip>
