Error Handling
Learn how to handle API errors gracefully and provide a great experience for your users.
Error Format
All errors return a consistent JSON structure:
{"error": {"code": "validation_error","message": "The request body contains invalid parameters","details": [{"field": "email","message": "Must be a valid email address"},{"field": "name","message": "Required field is missing"}],"requestId": "req_abc123xyz"}}
Error Codes
Common error codes and their meanings:
| Code | HTTP Status | Description |
|---|---|---|
validation_error | 400 | Request parameters are invalid |
authentication_error | 401 | Invalid or missing API key |
permission_denied | 403 | API key lacks required permissions |
not_found | 404 | Requested resource doesn't exist |
conflict | 409 | Resource already exists or conflict |
rate_limited | 429 | Too many requests |
server_error | 500 | Internal server error |
Handling Errors
Here's a comprehensive error handling example:
error-handling.ts
1import { Client, APIError, ValidationError, AuthenticationError } from '@your-api/sdk';23const client = new Client({ apiKey: process.env.API_KEY });45async function createUser(email: string, name: string) {6 try {7 const user = await client.users.create({ email, name });8 return { success: true, user };9 } catch (error) {10 if (error instanceof ValidationError) {11 // Handle validation errors12 console.error('Validation failed:', error.details);13 return {14 success: false,15 errors: error.details.map(d => ({16 field: d.field,17 message: d.message18 }))19 };20 }2122 if (error instanceof AuthenticationError) {23 // Handle auth errors - check your API key24 console.error('Authentication failed:', error.message);25 throw new Error('Please check your API configuration');26 }2728 if (error instanceof APIError) {29 // Handle other API errors30 console.error(`API Error [${error.code}]: ${error.message}`);3132 if (error.status === 409) {33 return { success: false, message: 'User already exists' };34 }3536 if (error.status >= 500) {37 // Server errors - safe to retry38 return { success: false, message: 'Service temporarily unavailable' };39 }40 }4142 // Unknown errors43 throw error;44 }45}
Include the request ID
When contacting support about an error, always include the
requestId from the error response. This helps us quickly locate and diagnose the issue.