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

# Error Handling

> A guide to understanding and handling errors from the AI Agents House SDK.

The AI Agents House SDK is designed to be resilient, but errors can still occur, especially during initial setup or due to network issues. This guide details the types of errors the SDK can produce and provides strategies for handling them gracefully in your application.

## Error Philosophy

### Non-Blocking by Default

The `track...` methods are designed to be non-blocking and fail silently (logging an error to the console) to prevent monitoring issues from crashing your core application logic. You can track an event, and even if the SDK fails to process or send it, your application will continue running.

### Critical Operations Throw

Operations that are critical to the SDK's function, such as initialization (`new AgentMonitor(...)` with invalid config) and manual flushing (`monitor.flush()`), will throw exceptions that you should handle.

### Graceful Degradation

If the SDK encounters persistent, unrecoverable errors (e.g., an invalid API key), it will log the error and effectively disable itself to avoid impacting your application's performance.

## Common Error Types

The SDK uses standard JavaScript `Error` objects, often with additional properties to provide more context.

### ValidationError

This error is thrown by the `AgentMonitor` constructor if the provided configuration is invalid.

* **name**: Always `'ValidationError'`.

* **message**: A summary of the validation failures. Example: `"Invalid configuration: apiKey: is required; batchSize: must be less than 1000"`

* **details**: An array of objects detailing specific validation issues. Useful for programmatic error handling.

* **path**: The configuration key that failed, e.g., `['batchSize']`

* **message**: The specific error message for that key.

**Example:**

```ts theme={null}
try {
  const monitor = new AgentMonitor({
    apiKey: '', // Invalid
    organizationId: 'your-org-id',
    batchSize: 9999 // Invalid
  });
} catch (error) {
  if (error.name === 'ValidationError') {
    console.error('Configuration Error:', error.message);
    console.error('Details:', error.details);
  }
}
```

### NetworkError / HttpRequestError

This error is thrown by `monitor.flush()` or `monitor.shutdown()` if the SDK fails to send an event batch after all retries.

* **name**: Typically `'HttpRequestError'` or similar
* **message**: Describes the failure, e.g., `"Failed to send events after 3 attempts. Final error: HTTP 500: Internal Server Error"`
* **statusCode**: HTTP status code of the final request (optional)
* **cause**: The underlying error object (optional)

**Example:**

```ts theme={null}
try {
  await monitor.flush();
} catch (error) {
  console.error('Failed to send monitoring data:', error.message);
}
```

## Error Handling Strategies

### In Your Application Code

Since `track...` methods don't throw, focus on handling configuration and shutdown errors.

<Steps>
  <Step title="Handle Configuration Errors">
    Wrap the `AgentMonitor` constructor in a try...catch block. A `ValidationError` is a critical setup issue.

    ```ts theme={null}
    let monitor;
    try {
    monitor = new AgentMonitor({ ... });
    } catch (error) {
    console.error('Failed to initialize AgentMonitor. Monitoring will be disabled.', error);
    monitor = createMockMonitor();
    }
    ```
  </Step>

  <Step title="Handle Shutdown Errors">
    Ensure monitoring data is flushed on shutdown, but don't block shutdown if flushing fails.

    ```ts theme={null}
    async function gracefulShutdown() {
    console.log('Shutting down...');
    try {
    await monitor.shutdown();
    console.log('Monitoring data flushed successfully.');
    } catch (error) {
    console.error('Could not flush all monitoring data during shutdown:', error.message);
    }
    process.exit(0);
    }

    process.on('SIGTERM', gracefulShutdown);
    ```
  </Step>

  <Step title="Monitor SDK Logs">
    In production, ensure your logging system:

    * Ingests logs from stdout/stderr
    * Alerts on logs with `level: 'error'` and prefix `[AgentGovernance]`
    * Flags frequent messages like "Failed to flush events"
  </Step>
</Steps>

## Troubleshooting Based on Errors

<AccordionGroup>
  <Accordion title="Error: HTTP 401 Unauthorized">
    This means your `apiKey` is incorrect, revoked, or invalid for the `organizationId`.

    **Action**: Verify credentials in the AI Agents House dashboard.
  </Accordion>

  <Accordion title="Error: HTTP 400 Bad Request">
    The SDK sent malformed or invalid data.

    **Action**: Enable `logLevel: 'debug'` and inspect payloads. Ensure custom events conform to schema.
  </Accordion>

  <Accordion title="Error: Request timeout or Network request failed">
    The SDK can't reach the AI Agents House API.

    **Action**: Check server network settings—firewalls, proxies, VPC rules blocking `api.aiagentshouse.com`.
  </Accordion>
</AccordionGroup>
