Error Handling
Learn how to handle errors from the Structurify API in your applications.
Error Types
| Error | HTTP Status | Description |
|---|---|---|
AuthenticationError | 401 | Invalid or missing API key |
NotFoundError | 404 | Resource not found |
ValidationError | 400 | Invalid request data |
InsufficientCreditsError | 402 | Not enough credits |
RateLimitError | 429 | Rate limit exceeded |
ServerError | 500 | Internal server error |
SDK Error Handling
- Python
- Node.js
from structurify import (
Structurify,
StructurifyError,
AuthenticationError,
NotFoundError,
ValidationError,
InsufficientCreditsError,
RateLimitError,
ServerError,
)
client = Structurify(api_key="sk_live_xxx")
try:
project = client.projects.get("proj_invalid")
except AuthenticationError:
print("Invalid API key. Check your credentials.")
except NotFoundError:
print("Project not found. Check the ID.")
except ValidationError as e:
print(f"Invalid request: {e.message}")
except InsufficientCreditsError:
print("Not enough credits. Please top up.")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds.")
except ServerError:
print("Server error. Please try again later.")
except StructurifyError as e:
print(f"API error: {e}")
import {
Structurify,
StructurifyError,
AuthenticationError,
NotFoundError,
ValidationError,
InsufficientCreditsError,
RateLimitError,
ServerError,
} from '@structurify/sdk';
const client = new Structurify({ apiKey: 'sk_live_xxx' });
try {
const project = await client.projects.get('proj_invalid');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key. Check your credentials.');
} else if (error instanceof NotFoundError) {
console.error('Project not found. Check the ID.');
} else if (error instanceof ValidationError) {
console.error(`Invalid request: ${error.message}`);
} else if (error instanceof InsufficientCreditsError) {
console.error('Not enough credits. Please top up.');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds.`);
} else if (error instanceof ServerError) {
console.error('Server error. Please try again later.');
} else if (error instanceof StructurifyError) {
console.error(`API error: ${error.message}`);
}
}
API Error Response
All API errors return this JSON format:
{
"error": "ErrorCode",
"message": "Human-readable description"
}
Retry Strategies
Rate Limiting
Implement exponential backoff for rate limits:
- Python
- Node.js
import time
from structurify import Structurify, RateLimitError
def with_retry(func, max_retries=3):
for attempt in range(max_retries):
try:
return func()
except RateLimitError as e:
if attempt < max_retries - 1:
wait = e.retry_after or (2 ** attempt)
print(f"Rate limited. Waiting {wait}s...")
time.sleep(wait)
else:
raise
# Usage
result = with_retry(lambda: client.extraction.run(project_id="proj_xxx"))
import { Structurify, RateLimitError } from '@structurify/sdk';
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (error instanceof RateLimitError && attempt < maxRetries - 1) {
const wait = error.retryAfter || Math.pow(2, attempt);
console.log(`Rate limited. Waiting ${wait}s...`);
await new Promise(r => setTimeout(r, wait * 1000));
} else {
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
// Usage
const result = await withRetry(() =>
client.extraction.run({ projectId: 'proj_xxx' })
);
Server Errors
For transient server errors (5xx), retry with backoff:
import time
from structurify import ServerError
def with_server_retry(func, max_retries=3):
for attempt in range(max_retries):
try:
return func()
except ServerError:
if attempt < max_retries - 1:
wait = 2 ** attempt
print(f"Server error. Retrying in {wait}s...")
time.sleep(wait)
else:
raise
Best Practices
- Always catch errors - Don't let unhandled exceptions crash your app
- Log error details - Include error codes and messages for debugging
- Use specific exceptions - Handle different errors appropriately
- Implement retries - Retry transient errors with backoff
- Monitor errors - Track error rates in your application
Common Issues
Invalid API Key
AuthenticationError: Invalid or missing API key
Solution: Verify your API key is correct and hasn't been revoked.
Project Not Found
NotFoundError: Project not found
Solution: Check the project ID. It may have been deleted.
Rate Limited
RateLimitError: Rate limit exceeded. Retry after 30s
Solution: Implement retry logic with the retry_after value.
Insufficient Credits
InsufficientCreditsError: Not enough credits
Solution: Top up credits in your dashboard.