Skip to main content

Error Response Format

All API errors follow a consistent JSON format to help you quickly identify and resolve issues.
Standard Error Response
{
  "success": false,
  "message": "Human-readable error description",
  "error": {
    "code": "ERROR_CODE",
    "details": "Additional context about the error",
    "field": "fieldName" // Present for validation errors
  }
}
success
boolean
Always false for error responses
message
string
A human-readable description of the error
error
object
Detailed error information

HTTP Status Codes

The Mindhunters API uses standard HTTP status codes to indicate success or failure.

Success Codes (2xx)

Status CodeMeaningDescription
200OKRequest succeeded
201CreatedResource successfully created

Client Error Codes (4xx)

Status CodeMeaningDescription
400Bad RequestMalformed request or invalid JSON
401UnauthorizedMissing or invalid authentication token
403ForbiddenValid token but insufficient permissions
404Not FoundResource or endpoint doesn’t exist
422Unprocessable EntityValidation failed on one or more fields
429Too Many RequestsRate limit exceeded

Server Error Codes (5xx)

Status CodeMeaningDescription
500Internal Server ErrorUnexpected server error occurred
502Bad GatewayService temporarily unavailable
503Service UnavailableServer overloaded or under maintenance

Common Errors

Authentication Errors

401 Unauthorized - Missing Token

{
  "success": false,
  "message": "Authentication required",
  "error": {
    "code": "MISSING_AUTH_TOKEN",
    "details": "No authorization header provided"
  }
}
Solution: Include the Authorization: Bearer YOUR_API_TOKEN header in your request.
curl -X GET https://your-tenant.mindhunters.ai/api/v1/calls \
  -H "Authorization: Bearer YOUR_API_TOKEN"

401 Unauthorized - Invalid Token

{
  "success": false,
  "message": "Invalid authentication token",
  "error": {
    "code": "INVALID_AUTH_TOKEN",
    "details": "The provided token is invalid or has been revoked"
  }
}
Solution: Verify your API token is correct and hasn’t been revoked. Generate a new token if necessary.

403 Forbidden - Insufficient Permissions

{
  "success": false,
  "message": "Insufficient permissions",
  "error": {
    "code": "FORBIDDEN",
    "details": "Your API token does not have permission to access this resource"
  }
}
Solution: Ensure your API token has the necessary permissions. Contact your workspace admin.

Validation Errors

422 Unprocessable Entity - Missing Required Field

{
  "success": false,
  "message": "Validation failed",
  "error": {
    "code": "VALIDATION_ERROR",
    "field": "agentId",
    "details": "The agentId field is required"
  }
}
Solution: Include all required fields in your request body.

422 Unprocessable Entity - Invalid Format

{
  "success": false,
  "message": "Validation failed",
  "error": {
    "code": "INVALID_FORMAT",
    "field": "participant.number",
    "details": "Phone number must be in E.164 format (e.g., +1234567890)"
  }
}
Solution: Ensure phone numbers are in E.164 format (+[country code][number]).
{
  "participant": {
    "number": "+1234567890"  // ✓ Valid
  }
}

422 Unprocessable Entity - Invalid UUID

{
  "success": false,
  "message": "Validation failed",
  "error": {
    "code": "INVALID_UUID",
    "field": "agentId",
    "details": "agentId must be a valid UUID"
  }
}
Solution: Ensure UUIDs are in the correct format (e.g., 550e8400-e29b-41d4-a716-446655440000).

Resource Errors

404 Not Found - Resource

{
  "success": false,
  "message": "Resource not found",
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "details": "Call with ID '550e8400-e29b-41d4-a716-446655440000' not found"
  }
}
Solution: Verify the resource ID is correct and the resource exists in your workspace.

404 Not Found - Endpoint

{
  "success": false,
  "message": "Endpoint not found",
  "error": {
    "code": "ENDPOINT_NOT_FOUND",
    "details": "The requested endpoint does not exist"
  }
}
Solution: Check the endpoint URL and HTTP method. Verify you’re using the correct API version.

Rate Limit Errors

429 Too Many Requests

{
  "success": false,
  "message": "Rate limit exceeded",
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "details": "You have exceeded the rate limit of 1000 requests per minute",
    "retryAfter": 45
  }
}
Solution: Implement exponential backoff and retry logic. Wait for the time specified in retryAfter (seconds).
async function makeRequestWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);

      if (response.status === 429) {
        const data = await response.json();
        const retryAfter = data.error.retryAfter || Math.pow(2, attempt);

        console.log(`Rate limited. Retrying after ${retryAfter}s...`);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      return response;
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
    }
  }
}

Server Errors

500 Internal Server Error

{
  "success": false,
  "message": "An unexpected error occurred",
  "error": {
    "code": "INTERNAL_SERVER_ERROR",
    "details": "Please try again later or contact support if the issue persists"
  }
}
Solution: This is a temporary server error. Retry the request. If the error persists, contact support@mindhunters.ai with the request details.

503 Service Unavailable

{
  "success": false,
  "message": "Service temporarily unavailable",
  "error": {
    "code": "SERVICE_UNAVAILABLE",
    "details": "The service is under maintenance or experiencing high load"
  }
}
Solution: Wait a few minutes and retry. Check the Mindhunters status page for ongoing incidents.

Error Handling Best Practices

Never assume a request succeeded. Always check the HTTP status code and handle errors appropriately.
const response = await fetch(url, options);

if (!response.ok) {
  const error = await response.json();
  console.error('API Error:', error.message);
  // Handle error appropriately
}
Implement exponential backoff for transient errors (5xx, 429). Don’t retry client errors (4xx) except after fixing the issue.Retry: 429, 500, 502, 503 Don’t retry: 400, 401, 403, 404, 422
Log errors with request IDs, timestamps, and relevant context for debugging.
console.error('API Error', {
  timestamp: new Date().toISOString(),
  endpoint: url,
  status: response.status,
  error: errorData
});
Validate request data on the client side before sending to reduce validation errors.
function validatePhoneNumber(number) {
  const e164Regex = /^\+[1-9]\d{1,14}$/;
  if (!e164Regex.test(number)) {
    throw new Error('Invalid phone number format');
  }
  return true;
}
Provide user-friendly error messages instead of exposing technical details.
try {
  await initiateCall(phoneNumber);
} catch (error) {
  if (error.status === 422) {
    showUserMessage('Please check the phone number format');
  } else if (error.status === 429) {
    showUserMessage('Too many requests. Please try again in a moment');
  } else {
    showUserMessage('An error occurred. Please try again');
  }
}
Track error rates and patterns in your monitoring system. Set up alerts for unusual error spikes.

Complete Error Handling Example

Here’s a comprehensive example with proper error handling:
class MindhuntersAPIClient {
  constructor(tenant, apiToken) {
    this.baseUrl = `https://${tenant}.mindhunters.ai/api/v1`;
    this.apiToken = apiToken;
  }

  async makeRequest(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const defaultOptions = {
      headers: {
        'Authorization': `Bearer ${this.apiToken}`,
        'Content-Type': 'application/json',
        ...options.headers
      }
    };

    const requestOptions = { ...defaultOptions, ...options };

    try {
      const response = await fetch(url, requestOptions);

      // Handle successful responses
      if (response.ok) {
        return await response.json();
      }

      // Parse error response
      const errorData = await response.json();

      // Handle specific error types
      switch (response.status) {
        case 400:
          throw new Error(`Bad Request: ${errorData.message}`);

        case 401:
          throw new Error('Authentication failed. Please check your API token.');

        case 403:
          throw new Error('Permission denied. Insufficient permissions.');

        case 404:
          throw new Error(`Not found: ${errorData.message}`);

        case 422:
          const field = errorData.error?.field || 'unknown';
          throw new Error(`Validation error in ${field}: ${errorData.message}`);

        case 429:
          const retryAfter = errorData.error?.retryAfter || 60;
          throw new Error(`Rate limit exceeded. Retry after ${retryAfter}s`);

        case 500:
        case 502:
        case 503:
          throw new Error('Server error. Please try again later.');

        default:
          throw new Error(`API Error: ${errorData.message}`);
      }

    } catch (error) {
      if (error instanceof TypeError) {
        throw new Error('Network error. Please check your connection.');
      }
      throw error;
    }
  }

  async initiateCall(agentId, phoneNumber, options = {}) {
    // Validate phone number format
    if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
      throw new Error('Phone number must be in E.164 format (e.g., +1234567890)');
    }

    return await this.makeRequest('/call', {
      method: 'POST',
      body: JSON.stringify({
        agentId,
        participant: { number: phoneNumber },
        ...options
      })
    });
  }
}

// Usage
const client = new MindhuntersAPIClient('your-tenant', 'YOUR_API_TOKEN');

try {
  const result = await client.initiateCall(
    '550e8400-e29b-41d4-a716-446655440000',
    '+1234567890'
  );
  console.log('Call initiated:', result.data.id);
} catch (error) {
  console.error('Failed to initiate call:', error.message);
}

Troubleshooting Guide

Quick Diagnostics

1

Check authentication

Verify your API token is correct and hasn’t been revoked. Test with a simple GET request.
2

Validate request format

Ensure your request body is valid JSON and includes all required fields.
3

Check tenant/subdomain

Verify you’re using the correct tenant in your base URL.
4

Review API logs

Check the Monitoring dashboard for detailed error information.
5

Test with cURL

Isolate the issue by testing with a simple cURL command.

Common Issues and Solutions

IssuePossible CauseSolution
CORS errorsCalling API from browser without proper setupUse server-side API calls or configure CORS in dashboard
Timeout errorsSlow network or server overloadImplement retry logic with exponential backoff
Invalid JSONMalformed request bodyValidate JSON before sending, use JSON.stringify()
Wrong content-typeMissing or incorrect Content-Type headerSet Content-Type: application/json
Inconsistent errorsNetwork instabilityCheck network connection, use retry logic

Getting Support

If you continue to experience errors after troubleshooting:

Check API Logs

Review detailed logs in your dashboard

Email Support

Contact support@mindhunters.ai with request details and log IDs

Documentation

Review endpoint-specific documentation

Status Page

Check status.mindhunters.ai for ongoing incidents

Information to Include

When contacting support, please provide:
  • Request ID from the error response or logs
  • Timestamp when the error occurred
  • Endpoint you were calling
  • Request payload (sanitized - remove sensitive data)
  • Error response received
  • Expected behavior

Next Steps