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

# Error Codes

> HTTP error codes and error response format

## Error response format

All error responses follow this structure:

```json theme={null}
{
  "code": 400,
  "message": "Missing required fields: model, task_type, input"
}
```

| Field     | Type     | Description                               |
| --------- | -------- | ----------------------------------------- |
| `code`    | `number` | The HTTP status code                      |
| `message` | `string` | A human-readable description of the error |

***

## Error codes

### 400 — Bad Request

The request body is malformed or missing required fields.

**Common causes**:

* Missing `model`, `task_type`, or `input` in the request body
* Unknown or unsupported `task_type`
* Invalid input parameters for the selected task type

```json theme={null}
{
  "code": 400,
  "message": "Missing required fields: model, task_type, input"
}
```

### 401 — Unauthorized

The API key is missing, invalid, or has been revoked.

**Common causes**:

* No `x-api-key` header in the request
* API key does not exist or has been deleted
* API key has been disabled

```json theme={null}
{
  "code": 401,
  "message": "Invalid API key"
}
```

### 402 — Payment Required

Your account does not have enough available credits to cover the task cost.

**How to fix**: [Top up credits](https://sunor.cc/dashboard/billing) in your dashboard.

```json theme={null}
{
  "code": 402,
  "message": "Insufficient credits: available 3, required 10"
}
```

### 404 — Not Found

The requested resource does not exist.

**Common causes**:

* Invalid task ID
* Task belongs to a different user

```json theme={null}
{
  "code": 404,
  "message": "Task not found"
}
```

### 429 — Too Many Requests

You have exceeded the [rate limit](/rate-limits).

**How to fix**: Wait for the duration in `retry_after_seconds` (or the `Retry-After` header) before retrying.

```json theme={null}
{
  "code": 429,
  "message": "Rate limit exceeded.",
  "retry_after_seconds": 60
}
```

### 500 — Internal Server Error

An unexpected error occurred on the server.

**What to do**: Retry the request after a short delay. If the error persists, contact support.

```json theme={null}
{
  "code": 500,
  "message": "Internal server error"
}
```

### 502 — Bad Gateway

The upstream AI provider returned an error or is temporarily unavailable.

**What to do**: Retry the request after a short delay. Credits are automatically refunded for failed tasks.

```json theme={null}
{
  "code": 502,
  "message": "Upstream provider error"
}
```

***

## Handling errors

<Tip>
  Always check the HTTP status code of the response before parsing the body. For `5xx` errors, implement exponential backoff with a maximum of 3 retries.
</Tip>

### Example error handling

<CodeGroup>
  ```python Python theme={null}
  import requests
  import time

  def create_task(api_key, payload, max_retries=3):
      for attempt in range(max_retries):
          response = requests.post(
              "https://sunor.cc/api/v1/task",
              headers={
                  "Content-Type": "application/json",
                  "x-api-key": api_key,
              },
              json=payload,
          )

          if response.status_code == 202:
              return response.json()["data"]
          elif response.status_code == 429:
              retry_after = int(response.headers.get("Retry-After", 30))
              time.sleep(retry_after)
          elif response.status_code >= 500:
              time.sleep(2 ** attempt)
          else:
              error = response.json()
              raise Exception(f"API error {error['code']}: {error['message']}")

      raise Exception("Max retries exceeded")
  ```

  ```javascript Node.js theme={null}
  async function createTask(apiKey, payload, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      const response = await fetch("https://sunor.cc/api/v1/task", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": apiKey,
        },
        body: JSON.stringify(payload),
      });

      if (response.status === 202) {
        const json = await response.json();
        return json.data;
      } else if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get("Retry-After") || "30");
        await new Promise((r) => setTimeout(r, retryAfter * 1000));
      } else if (response.status >= 500) {
        await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
      } else {
        const error = await response.json();
        throw new Error(`API error ${error.code}: ${error.message}`);
      }
    }
    throw new Error("Max retries exceeded");
  }
  ```
</CodeGroup>
