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

# Error Handling

> Dashtray API error codes and responses

# Error Handling

Understand and handle errors from the Dashtray API.

## Error Response Format

All errors return a consistent JSON format:

```json theme={null}
{
  "ok": false,
  "error": "Human-readable description",
  "code": "ERROR_CODE",
  "statusCode": 400
}
```

## HTTP Status Codes

| Code | Meaning | Action |
| - | - | - |
| 200 | OK | Request succeeded |
| 400 | Bad Request | Check your input |
| 401 | Unauthorized | Check your API key |
| 404 | Not Found | Resource doesn't exist |
| 429 | Too Many Requests | Wait and retry |
| 500 | Server Error | Retry later |

## Error Codes

### VALIDATION\_ERROR (400)

Invalid or missing request parameters.

```json theme={null}
{
  "ok": false,
  "error": "title is required and must be string",
  "code": "VALIDATION_ERROR",
  "statusCode": 400
}
```

**Solutions:**

* Check that all required fields are present (`title` and `body`)
* Verify field types (string vs number, etc.)
* Ensure the request body is valid JSON

### UNAUTHORIZED (401)

Invalid or missing API key.

```json theme={null}
{
  "ok": false,
  "error": "Invalid API key",
  "code": "UNAUTHORIZED",
  "statusCode": 401
}
```

**Solutions:**

* Verify the API key format starts with `sk_`
* Check the `Authorization: Bearer` header is set correctly
* Ensure the key hasn't been revoked
* Generate a new key if uncertain

### RATE\_LIMIT\_EXCEEDED (429)

You've exceeded your plan's per-minute rate limit.

```json theme={null}
{
  "ok": false,
  "error": "Rate limit exceeded: 100 requests per minute",
  "code": "RATE_LIMIT_EXCEEDED",
  "statusCode": 429
}
```

**Response Headers:**

```
Retry-After: 60
```

**Solutions:**

* Wait 60 seconds for the window to reset
* Space out requests to stay under the limit
* Upgrade your plan for higher limits

### NOT\_FOUND (404)

The requested resource doesn't exist.

```json theme={null}
{
  "ok": false,
  "error": "Alert not found",
  "code": "NOT_FOUND",
  "statusCode": 404
}
```

**Solutions:**

* Verify the resource ID is correct
* Ensure the resource hasn't been deleted
* Check that you have access to the resource

### INTERNAL\_ERROR (500)

Server-side error. Usually temporary.

```json theme={null}
{
  "ok": false,
  "error": "Internal server error",
  "code": "INTERNAL_ERROR",
  "statusCode": 500
}
```

**Solutions:**

* Retry the request after a few seconds
* Use exponential backoff for retries
* Contact support if the error persists

## Handling Errors in Code

### JavaScript

```javascript theme={null}
async function sendNotification(title, body) {
  try {
    const response = await fetch('https://api.dashtray.app/api/v1/notifications/send', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.DASHTRAY_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ title, body })
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(`[${data.code}] ${data.error}`);
    }

    return data.notification;
  } catch (error) {
    console.error('Failed to send notification:', error.message);
    // Handle error appropriately
  }
}
```

### Python

```python theme={null}
import requests

def send_notification(title, body):
    headers = {
        'Authorization': f'Bearer {os.environ.get("DASHTRAY_API_KEY")}',
        'Content-Type': 'application/json'
    }
    
    response = requests.post(
        'https://api.dashtray.app/api/v1/notifications/send',
        headers=headers,
        json={'title': title, 'body': body}
    )
    
    if not response.ok:
        data = response.json()
        raise Exception(f"[{data['code']}] {data['error']}")
    
    return response.json()['notification']
```

### cURL

```bash theme={null}
response=$(curl -X POST https://api.dashtray.app/api/v1/notifications/send \
  -H "Authorization: Bearer $DASHTRAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"title": "Hello", "body": "World"}')

if echo "$response" | grep -q '"ok":false'; then
  echo "Error: $(echo $response | jq .message)"
  exit 1
fi
```

## Retry Strategy

Implement exponential backoff for retries:

```javascript theme={null}
async function sendWithRetry(title, description, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await sendNotification(title, description);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // Exponential backoff: 1s, 2s, 4s
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
```

## Common Mistakes

<Warning>
  **Don't hardcode API keys in code.** Use environment variables.
</Warning>

```javascript theme={null}
// ❌ Bad
const apiKey = "sk_test_...";

// ✅ Good
const apiKey = process.env.DASHTRAY_API_KEY;
```

<Warning>
  **Don't ignore 429 errors.** Respect rate limits.
</Warning>

```javascript theme={null}
// ❌ Bad
try {
  // send request
} catch (error) {
  // try again immediately
}

// ✅ Good
if (response.status === 429) {
  const resetTime = parseInt(response.headers['x-ratelimit-reset']);
  await delay(resetTime - Date.now());
}
```

## Support

Having issues? Check:

* [Quickstart](/quickstart)
* [Authentication guide](/authentication)
* [API Reference](/api-reference/overview)
* [GitHub Issues](https://github.com/bhupeshpradhan/dashtray/issues)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.