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

# Error Handling

> Understanding API errors and how to handle them

## Error Response Format

All API errors follow a consistent JSON format:

```json theme={null}
{
  "error": "Error Type",
  "message": "Human-readable description of what went wrong",
  "code": "SPECIFIC_ERROR_CODE",
  "details": {}
}
```

## HTTP Status Codes

The Wallbit API uses standard HTTP status codes to indicate the success or failure of requests.

### Success Codes

| Code             | Description                             |
| ---------------- | --------------------------------------- |
| `200 OK`         | Request succeeded                       |
| `201 Created`    | Resource created successfully           |
| `204 No Content` | Request succeeded, no content to return |

### Client Error Codes

| Code                       | Description                              |
| -------------------------- | ---------------------------------------- |
| `400 Bad Request`          | Invalid request parameters               |
| `401 Unauthorized`         | Missing or invalid API key               |
| `403 Forbidden`            | API key lacks required permissions       |
| `404 Not Found`            | Resource doesn't exist                   |
| `422 Unprocessable Entity` | Request is valid but cannot be processed |
| `429 Too Many Requests`    | Rate limit exceeded                      |

### Server Error Codes

| Code                        | Description                     |
| --------------------------- | ------------------------------- |
| `500 Internal Server Error` | Something went wrong on our end |
| `502 Bad Gateway`           | Upstream service error          |
| `503 Service Unavailable`   | API is temporarily unavailable  |

## Common Errors

### Authentication Errors

<Accordion title="401 Unauthorized" icon="lock">
  ```json theme={null}
  {
    "error": "Unauthorized",
    "message": "Invalid or missing API key",
    "code": "INVALID_API_KEY"
  }
  ```

  **Solution:** Check that you're including the `X-API-Key` header with a valid API key.
</Accordion>

<Accordion title="403 Forbidden" icon="ban">
  ```json theme={null}
  {
    "error": "Forbidden",
    "message": "API key does not have permission for this operation",
    "code": "INSUFFICIENT_PERMISSIONS"
  }
  ```

  **Solution:** Create an API key with the required permissions for this endpoint.
</Accordion>

### Validation Errors

<Accordion title="400 Bad Request" icon="circle-xmark">
  ```json theme={null}
  {
    "error": "Bad Request",
    "message": "Invalid request parameters",
    "code": "VALIDATION_ERROR",
    "details": {
      "field": "amount",
      "reason": "Must be a positive number"
    }
  }
  ```

  **Solution:** Check the `details` field for specific validation issues and correct your request.
</Accordion>

### Business Logic Errors

<Accordion title="422 Unprocessable Entity" icon="triangle-exclamation">
  ```json theme={null}
  {
    "error": "Unprocessable Entity",
    "message": "Insufficient balance for this operation",
    "code": "INSUFFICIENT_BALANCE",
    "details": {
      "available": 100.00,
      "required": 150.00
    }
  }
  ```

  **Solution:** This indicates a business rule violation. Check the specific error code and adjust your request accordingly.
</Accordion>

## Error Handling Best Practices

<AccordionGroup>
  <Accordion title="Always Check Status Codes" icon="check">
    Don't assume requests succeed. Always check the HTTP status code before processing the response:

    ```javascript theme={null}
    const response = await fetch(url, options);

    if (!response.ok) {
      const error = await response.json();
      console.error(`API Error: ${error.message} (${error.code})`);
      // Handle error appropriately
    }
    ```
  </Accordion>

  <Accordion title="Log Error Details" icon="file-lines">
    Log the full error response for debugging:

    ```javascript theme={null}
    catch (error) {
      console.error('API Error:', {
        status: error.status,
        error: error.error,
        message: error.message,
        code: error.code,
        details: error.details
      });
    }
    ```
  </Accordion>

  <Accordion title="User-Friendly Messages" icon="message">
    Don't show raw API errors to users. Map error codes to friendly messages:

    ```javascript theme={null}
    const errorMessages = {
      'INSUFFICIENT_BALANCE': 'You don\'t have enough funds for this transaction.',
      'INVALID_API_KEY': 'Authentication failed. Please check your settings.',
      'RATE_LIMIT_EXCEEDED': 'Too many requests. Please try again in a moment.'
    };

    const userMessage = errorMessages[error.code] || 'Something went wrong. Please try again.';
    ```
  </Accordion>
</AccordionGroup>

## Error Code Reference

| Code                       | Description                        |
| -------------------------- | ---------------------------------- |
| `INVALID_API_KEY`          | API key is missing or invalid      |
| `INSUFFICIENT_PERMISSIONS` | API key lacks required permissions |
| `VALIDATION_ERROR`         | Request parameters are invalid     |
| `INSUFFICIENT_BALANCE`     | Not enough funds for the operation |
| `ASSET_NOT_FOUND`          | Requested asset doesn't exist      |
| `TRADE_FAILED`             | Trade could not be executed        |
| `RATE_LIMIT_EXCEEDED`      | Too many requests                  |
| `INTERNAL_ERROR`           | Server-side error                  |
