HomeDocumentation

Error Handling

The Telesoft Healthcare API uses standard HTTP status codes and returns detailed error objects to help you troubleshoot issues with your API requests.

Error Response Format

All API errors follow a consistent format, designed to provide clear information about what went wrong and how to fix it.

{
  "error": {
    "type": "invalid_request_error",
    "code": "parameter_missing",
    "message": "Required parameter 'patientData.age' is missing",
    "param": "patientData.age",
    "requestId": "req_7f9a2d7e8b3c",
    "details": {
      "requiredFields": ["age", "sex", "symptoms"],
      "providedFields": ["sex", "symptoms"]
    },
    "documentation": "/waitlist"
  }
}
FieldDescription
error.typeThe high-level category of error (e.g., authentication_error, invalid_request_error)
error.codeA specific error code that uniquely identifies the error
error.messageA human-readable message explaining the error
error.paramIf applicable, the specific parameter that caused the error
error.requestIdA unique identifier for the request, useful when contacting support
error.detailsAdditional context-specific information about the error
error.documentationA link to documentation about this specific error

HTTP Status Codes

The Telesoft API uses standard HTTP status codes to indicate the success or failure of API requests.

2xx - Success

Status CodeDescription
200 OKRequest succeeded. The response body contains the requested data.
201 CreatedResource created successfully. Used for POST requests that create new resources.
204 No ContentRequest succeeded but no content to return. Often used for DELETE operations.

4xx - Client Errors

Status CodeDescription
400 Bad RequestInvalid request format or parameters. Check the error details for specific validation errors.
401 UnauthorizedAuthentication failed or not provided. Check your API key or OAuth token.
403 ForbiddenThe authenticated user does not have permission to access the requested resource.
404 Not FoundThe requested resource does not exist.
422 Unprocessable EntityThe request was well-formed but contains semantic errors. Often used for medical data validation issues.
429 Too Many RequestsRate limit exceeded. See the Rate Limiting documentation for more details.

5xx - Server Errors

Status CodeDescription
500 Internal Server ErrorAn error occurred on the server. If this persists, please contact support with the requestId.
502 Bad GatewayThe server received an invalid response from an upstream service.
503 Service UnavailableThe server is temporarily unavailable, usually due to maintenance or high load.

Error Types

Error types categorize the nature of the error to help you determine how to address it in your application.

authentication_error

Authentication-related errors, such as invalid API keys or expired tokens.

Common error codes:

  • invalid_api_key - The API key provided is invalid or does not exist
  • expired_token - The OAuth token has expired and needs to be refreshed
  • invalid_scope - The token does not have the required scope for this operation

invalid_request_error

Errors related to the format or content of the request.

Common error codes:

  • parameter_missing - A required parameter was not provided
  • parameter_invalid - A parameter was provided with an invalid value
  • json_parse_error - The request body contained invalid JSON

rate_limit_error

Errors related to exceeding the rate limit for API requests.

Common error codes:

  • rate_limit_exceeded - You've exceeded the rate limit for this type of request
  • concurrent_request_limit - Too many concurrent requests for your account

medical_data_error

Errors specific to medical data validation or processing.

Common error codes:

  • medical_data_insufficient - Not enough medical data to perform the requested analysis
  • medical_data_inconsistent - The medical data contains contradictory information
  • medical_term_unknown - A provided medical term is not recognized

internal_error

Errors that occur within the Telesoft system.

Common error codes:

  • service_unavailable - A required service is temporarily unavailable
  • model_execution_error - An error occurred while executing the AI model
  • database_error - An error occurred when accessing the database

Error Handling Best Practices

Implementing Robust Error Handling

Here's an example of a robust error handling implementation using the JavaScript SDK:

import { TelesoftAI, TelesoftAPIError } from '@telesoft/healthcare-sdk';

const telesoft = new TelesoftAI({
  apiKey: 'YOUR_API_KEY',
  environment: 'production'
});

async function handleDiagnosticRequest(patientData) {
  try {
    const result = await telesoft.diagnostics.analyze({
      patientData,
      options: {
        includeConfidenceScores: true
      }
    });
    
    return result;
  } catch (error) {
    if (error instanceof TelesoftAPIError) {
      // Handle API-specific errors
      switch (error.type) {
        case 'authentication_error':
          console.error('Authentication error:', error.message);
          // Refresh credentials or redirect to login
          break;
          
        case 'rate_limit_error':
          const retryAfter = error.headers['retry-after'];
          console.error(`Rate limit exceeded. Retry after ${retryAfter} seconds`);
          // Implement retry logic with exponential backoff
          break;
          
        case 'invalid_request_error':
          console.error('Invalid request:', error.message);
          if (error.param) {
            console.error(`Problem with parameter: ${error.param}`);
          }
          if (error.details) {
            console.error('Error details:', error.details);
          }
          // Fix request parameters
          break;
          
        case 'medical_data_error':
          console.error('Medical data issue:', error.message);
          // Prompt for additional information
          break;
          
        default:
          console.error(`Telesoft API error: ${error.type} - ${error.message}`);
          // Log error for further investigation
      }
      
      // Always include the requestId when contacting support
      console.error(`Request ID: ${error.requestId}`);
      
    } else {
      // Handle network errors or other client-side issues
      console.error('Client-side error:', error);
    }
    
    throw error; // Re-throw or handle according to your application's needs
  }
}

Retrying Failed Requests

Some errors are transient and can be resolved by retrying the request. Here's an example retry implementation:

async function retryableRequest(requestFn, maxRetries = 3, initialDelay = 1000) {
  let attempts = 0;
  let delay = initialDelay;
  
  while (attempts < maxRetries) {
    try {
      return await requestFn();
    } catch (error) {
      attempts++;
      
      // Determine if the error is retryable
      const isRetryable = 
        error instanceof TelesoftAPIError && 
        (error.type === 'rate_limit_error' || 
         error.status === 503 || 
         error.status === 502);
      
      if (!isRetryable || attempts >= maxRetries) {
        throw error; // Not retryable or max retries reached
      }
      
      // Calculate delay with exponential backoff
      // Uses the Retry-After header if available
      if (error.headers && error.headers['retry-after']) {
        delay = parseInt(error.headers['retry-after'], 10) * 1000;
      } else {
        delay = delay * (1.5 + Math.random()); // Exponential backoff with jitter
      }
      
      console.warn(`Request failed. Retrying in ${delay/1000} seconds. Attempt ${attempts} of ${maxRetries}.`);
      
      // Wait before retrying
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

💡 Pro Tip

Only retry requests that have a reasonable chance of succeeding on a subsequent attempt. Don't retry requests with validation errors or authentication failures unless you've fixed the underlying issue.

Common Error Scenarios

Missing or Invalid Patient Data

// Error Response (422 Unprocessable Entity)
{
  "error": {
    "type": "medical_data_error",
    "code": "medical_data_insufficient",
    "message": "Insufficient medical data to perform diagnostic analysis",
    "requestId": "req_3f9a2d7e8b3c",
    "details": {
      "requiredFields": ["age", "sex", "symptoms"],
      "missingFields": ["symptoms"],
      "recommendations": "Provide at least 3 symptoms for accurate diagnosis"
    }
  }
}

Solution: Ensure you're providing all required fields with valid values. Check the error.details for specific guidance on what's missing or invalid.

Rate Limiting

// Error Response (429 Too Many Requests)
{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded for diagnostics.analyze",
    "requestId": "req_5f9a2d7e8b3c",
    "details": {
      "limit": 100,
      "remaining": 0,
      "reset": 1612345678
    }
  }
}

// Response Headers
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1612345678

Solution: Implement rate limiting in your application based on the headers provided. Use exponential backoff for retries. Consider upgrading your plan if you consistently hit rate limits.

Authentication Failures

// Error Response (401 Unauthorized)
{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "Invalid API key provided",
    "requestId": "req_2f9a2d7e8b3c"
  }
}

Solution: Ensure you're using the correct API key for the environment you're accessing (test vs. production). Check that your API key is valid and active in the developer portal.