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

# Error Handling

> Learn how to handle and troubleshoot errors returned by the Routeway API.

Routeway uses standard HTTP response codes to indicate the success or failure of an API request. Error responses contain a detailed JSON body that mirrors the OpenAI error schema, making it easy to parse errors programmatically.

## Error Response Schema

All API errors return a standard JSON object containing an `error` payload:

```json theme={null}
{
  "error": {
    "message": "Invalid or missing API key",
    "type": "invalid_request_error",
    "code": 401,
    "tip": "Ensure your API key is correctly passed in the Authorization header: Bearer <KEY>",
    "trace_id": "req_01j0x7p6..."
  }
}
```

### Fields

| Field      | Type             | Description                                                                             |
| :--------- | :--------------- | :-------------------------------------------------------------------------------------- |
| `message`  | `string`         | A human-readable description of the error.                                              |
| `type`     | `string`         | The category of error (e.g., `invalid_request_error`, `rate_limit_error`, `api_error`). |
| `code`     | `integer/string` | The HTTP status code or a custom error code.                                            |
| `tip`      | `string`         | An optional helpful suggestion to quickly resolve the error.                            |
| `trace_id` | `string`         | A unique identifier for the request, useful when contacting support.                    |

***

## HTTP Status Codes

| Status Code | Error Type              | Description                                                                                              |
| :---------- | :---------------------- | :------------------------------------------------------------------------------------------------------- |
| **400**     | `invalid_request_error` | **Bad Request** - Invalid JSON body, missing required parameters, or invalid parameters.                 |
| **401**     | `authentication_error`  | **Unauthorized** - Missing or incorrect API key, or the key has been revoked.                            |
| **403**     | `permission_error`      | **Forbidden** - The key lacks permissions for the requested model or endpoint.                           |
| **404**     | `invalid_request_error` | **Not Found** - The requested endpoint does not exist.                                                   |
| **422**     | `invalid_request_error` | **Unprocessable Entity** - Schema validation failed, or the input tokens exceeded the model's limit.     |
| **429**     | `rate_limit_error`      | **Too Many Requests** - You have exceeded your tier rate limits or custom key limits.                    |
| **500**     | `api_error`             | **Internal Server Error** - An unexpected error occurred on Routeway's servers.                          |
| **502**     | `provider_error`        | **Bad Gateway** - The downstream AI provider (e.g., Anthropic, DeepSeek) returned an error or timed out. |

***

## Catching Errors in Code

Since Routeway uses OpenAI-compatible responses, the official OpenAI SDKs will automatically parse and throw structured exceptions.

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const { OpenAI } = require("openai");

    const client = new OpenAI({
      base_url: "https://api.routeway.ai/v1",
      api_key: process.env.ROUTEWAY_API_KEY,
    });

    async function run() {
      try {
        const response = await client.chat.completions.create({
          model: "gpt-4o-mini",
          messages: [{ role: "user", content: "Hello!" }],
        });
      } catch (error) {
        if (error instanceof OpenAI.APIError) {
          console.error(`Status: ${error.status}`); // e.g., 401
          console.error(`Message: ${error.message}`);
          console.error(`Type: ${error.type}`);
        } else {
          console.error("Non-API Error:", error);
        }
      }
    }

    run();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI, APIError

    client = OpenAI(
        base_url="https://api.routeway.ai/v1",
        api_key=os.getenv("ROUTEWAY_API_KEY")
    )

    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": "Hello!"}]
        )
    except APIError as e:
        print(f"Status: {e.status_code}") # e.g., 401
        print(f"Message: {e.message}")
        print(f"Type: {e.code}")
    except Exception as e:
        print(f"Non-API Error: {e}")
    ```
  </Tab>
</Tabs>
