error handling
This guide explains how errors are represented in the Instinct API and provides best practices for handling them in your applications.
error response format
All API errors follow a consistent JSON format:
{
"success": false,
"error": {
"code": "error_code",
"message": "Human readable error description",
"details": {
// Additional context-specific information about the error
}
}
}
The error object contains:
code
: A unique string identifier for the error typemessage
: A human-readable description of what went wrongdetails
: Optional object containing additional information about the error
http status codes
The API uses standard HTTP status codes to indicate the general category of response:
Status Code | Description |
---|---|
200 | Success - The request was processed successfully |
400 | Bad Request - Invalid syntax or parameters |
401 | Unauthorized - Authentication required or failed |
403 | Forbidden - Authentication succeeded but insufficient access |
404 | Not Found - The requested resource doesn't exist |
409 | Conflict - The request conflicts with current state |
422 | Unprocessable Entity - Request validation failed |
429 | Too Many Requests - Rate limit exceeded |
500 | Internal Server Error - Something went wrong on the server |
503 | Service Unavailable - The service is temporarily unavailable |
common error codes
Here are some common error codes you might encounter:
general errors
invalid_request
: The request has invalid syntax or is missing required fieldsinvalid_parameter
: A parameter has an invalid valueresource_not_found
: The requested resource doesn't existrate_limit_exceeded
: Too many requests sent in a given time periodinternal_error
: An unexpected error occurred on the server
authentication errors
authentication_required
: The request requires authenticationinvalid_credentials
: The provided authentication credentials are invalidexpired_token
: The authentication token has expired
stream processing errors
stream_not_found
: The specified stream doesn't existinvalid_stream_id
: The stream ID format is invalidstream_already_exists
: A stream with this ID already existsinvalid_node_config
: Node configuration is invalidinvalid_pipe_config
: Pipe configuration is invalidcycle_detected
: The pipeline contains cycles
hardware errors
device_not_found
: The specified device wasn't foundhardware_error
: A hardware-related error occurredoperation_not_supported
: The operation isn't supported by the hardwareelectrode_error
: An issue with electrode operationmotor_error
: An issue with motor operation
error handling best practices
1. always check the success flag
Always check the success
field in the response to determine if the operation succeeded:
fetch('http://localhost:42069/stream/streams')
.then((response) => response.json())
.then((data) => {
if (data.success) {
// Handle successful response
processStreams(data.streams);
} else {
// Handle error
handleError(data.error);
}
});
2. implement granular error handling
Handle different error codes appropriately:
function handleError(error) {
switch (error.code) {
case 'resource_not_found':
showNotification('The requested resource could not be found');
break;
case 'invalid_parameter':
showFieldError(error.details.field, error.details.message);
break;
case 'authentication_required':
redirectToLogin();
break;
default:
showGenericError(error.message);
}
}
3. implement exponential backoff for retries
When encountering transient errors (like rate limits or server errors), implement exponential backoff:
async function fetchWithRetry(url, options, maxRetries = 3) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch(url, options);
const data = await response.json();
if (data.success) {
return data;
}
// If it's a rate limit error, retry with backoff
if (data.error.code === 'rate_limit_exceeded') {
const backoffTime = Math.pow(2, retries) * 1000;
await new Promise((resolve) => setTimeout(resolve, backoffTime));
retries++;
continue;
}
// For other errors, just return the error
return data;
} catch (err) {
// Network-level error, retry with backoff
const backoffTime = Math.pow(2, retries) * 1000;
await new Promise((resolve) => setTimeout(resolve, backoffTime));
retries++;
}
}
return {
success: false,
error: {
code: 'max_retries_exceeded',
message: 'Request failed after maximum retries',
},
};
}
4. log errors for debugging
Keep detailed logs of API errors to help with debugging:
function logApiError(endpoint, requestData, error) {
console.error(`API Error on ${endpoint}:`, {
timestamp: new Date().toISOString(),
request: requestData,
errorCode: error.code,
errorMessage: error.message,
errorDetails: error.details,
});
}
5. show user-friendly messages
Translate technical error messages into user-friendly language:
const errorMessages = {
invalid_parameter: 'One of the fields contains an invalid value',
resource_not_found: "We couldn't find what you're looking for",
stream_already_exists: 'A data stream with this name already exists',
rate_limit_exceeded: 'Please wait a moment before trying again',
};
function getUserFriendlyMessage(error) {
return (
errorMessages[error.code] || error.message || 'An unexpected error occurred'
);
}