Error Handling

Understanding and handling API errors is crucial for building robust integrations with AnyPay Tanzania services.

HTTP Status Codes

Our API uses standard HTTP status codes to indicate the success or failure of requests:

Status Code Description
200 Success - Request processed successfully
400 Bad Request - Invalid request parameters
401 Unauthorized - Invalid or missing API token
403 Forbidden - Insufficient permissions
404 Not Found - Endpoint does not exist
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Server-side error

Error Response Format

All error responses follow a consistent JSON format:

{
  "code": 400,
  "success": false,
  "message": "Error description",
  "errors": [
    {
      "field": "sender_id",
      "message": "Sender ID is required"
    }
  ]
}

Error Fields

  • code: HTTP status code
  • success: Always false for errors
  • message: Human-readable error description
  • errors: Array of detailed field-level errors (optional)

Common Error Scenarios

Authentication Errors

{
  "code": 401,
  "success": false,
  "message": "Invalid API token"
}

Validation Errors

{
  "code": 400,
  "success": false,
  "message": "Validation failed",
  "errors": [
    {
      "field": "contacts",
      "message": "Invalid phone number format"
    },
    {
      "field": "message",
      "message": "Message cannot be empty"
    }
  ]
}

Insufficient Balance

{
  "code": 402,
  "success": false,
  "message": "Insufficient balance. Please top up your account."
}

Handling Errors in Code

JavaScript Example

fetch('https://anypaytanzania.com/api/sms/send/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_TOKEN'
  },
  body: JSON.stringify(data)
})
.then(response => {
  if (!response.ok) {
    return response.json().then(error => {
      throw new Error(error.message);
    });
  }
  return response.json();
})
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error.message));

Python Example

import requests

try:
    response = requests.post(url, json=data, headers=headers)
    response.raise_for_status()  # Raises an exception for 4xx/5xx status codes
    result = response.json()
    print('Success:', result)
except requests.exceptions.HTTPError as e:
    error_data = e.response.json()
    print('Error:', error_data['message'])
except requests.exceptions.RequestException as e:
    print('Network error:', str(e))

Best Practices

  • Always check the HTTP status code before processing the response
  • Implement proper error handling in your application
  • Log errors for debugging purposes
  • Provide meaningful error messages to your users
  • Handle rate limiting gracefully with exponential backoff