Understanding and handling API errors effectively
All API errors follow a consistent JSON format:
{
"error": "error_type",
"message": "Human-readable error description",
"status": 400
}
Status Code | Description | Common Causes |
---|---|---|
400
|
Bad Request |
|
401
|
Unauthorized |
|
403
|
Forbidden |
|
429
|
Too Many Requests |
|
500
|
Internal Server Error |
|
Our camera.js library provides built-in error handling for common issues:
try {
const camera = new VerifyCamera((photoData) => {
if (photoData) {
console.log('Photo captured successfully');
}
});
await camera.start();
} catch (error) {
switch (error.name) {
case 'NotAllowedError':
console.error('Camera permission denied');
break;
case 'NotFoundError':
console.error('No camera available');
break;
case 'NotSupportedError':
console.error('Camera API not supported');
break;
default:
console.error('Camera error:', error);
}
}
When making direct API calls, handle errors appropriately:
async function verifyFaces(reference, selfie) {
try {
const formData = new FormData();
formData.append('reference', reference);
formData.append('selfie', selfie);
const response = await fetch('https://api.example.com/api/v2/verify', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
// Handle validation errors
if (error.message.includes('No face detected')) {
console.error('No face found in image');
} else if (error.message.includes('Multiple faces')) {
console.error('Multiple faces detected');
} else {
console.error('Invalid request:', error.message);
}
break;
case 401:
console.error('Authentication failed:', error.message);
break;
case 429:
console.error('Rate limit exceeded:', error.message);
break;
default:
console.error('API error:', error.message);
}
throw new Error(error.message);
}
const result = await response.json();
if (result.is_spoof) {
console.error('Spoof detected in selfie');
return;
}
return result;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}