Error Handling

Understanding and handling API errors effectively

HTTP Status Codes

Status Code Meaning Description
200 Success Request completed successfully
400 Bad Request Missing required fields, invalid key, file too large
405 Method Not Allowed Using GET instead of POST
429 Too Many Requests Rate limit exceeded (wait 3 seconds)
500 Internal Server Error Email sending failed, database error

Error Response Format

All error responses follow this structure:

{
  "success": false,
  "message": "General error message",
  "errors": {
    "__all__": ["General errors not tied to specific fields"],
    "field_name": ["Field-specific error messages"]
  }
}

Common Errors

Missing Required Fields (400)

{
  "success": false,
  "message": "Missing required fields.",
  "errors": {
    "__all__": ["Missing required fields."],
    "email": ["This field is required."],
    "access_key": ["This field is required."],
    "message": ["This field is required."]
  }
}

Invalid Verification Key (400)

{
  "success": false,
  "message": "Invalid verification key.",
  "errors": {
    "access_key": ["Invalid verification key."]
  }
}

Domain Mismatch (400)

{
  "success": false,
  "message": "Verification key domain mismatch.",
  "errors": {
    "access_key": ["Verification key domain mismatch."],
    "__all__": ["Domain does not match."]
  }
}

Too Many Files (400)

{
  "success": false,
  "message": "Too many files. Max 10.",
  "errors": {
    "_files": ["Too many files. Maximum allowed is 10."]
  }
}

File Too Large (400)

{
  "success": false,
  "message": "File 'document.pdf' too large. Max 10 MB.",
  "errors": {
    "attachment": ["'document.pdf' exceeds size limit of 10 MB."]
  }
}

Rate Limit Exceeded (429)

{
  "error": "Your first request ran successfully. Too many requests were received — please wait 3 seconds before trying again."
}

Handling Errors in Code

JavaScript Example

async function submitForm(data) {
  try {
    const response = await fetch('/api/contact-api/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });

    const result = await response.json();

    if (result.success) {
      // Handle success
      showSuccessMessage(result.message);
    } else {
      // Handle field errors
      if (result.errors) {
        Object.keys(result.errors).forEach(field => {
          displayFieldError(field, result.errors[field]);
        });
      } else {
        showErrorMessage(result.message);
      }
    }
  } catch (error) {
    // Handle network errors
    showErrorMessage('Network error. Please try again.');
  }
}

Python Example

import requests
try:
    response = requests.post(url, json=payload)
    response.raise_for_status()
    
    data = response.json()
    
    if data.get('success'):
        print(f"Success: {data['message']}")
    else:
        print(f"Error: {data['message']}")
        if 'errors' in data:
            for field, errors in data['errors'].items():
                print(f"  {field}: {', '.join(errors)}")
                
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e}")
except requests.exceptions.RequestException as e:
    print(f"Network Error: {e}")

Best Practices

Error Handling Tips
  • Always check the success field in responses
  • Display field-specific errors near the input fields
  • Show general errors in a prominent location
  • Implement retry logic for network errors
  • Handle rate limiting with appropriate delays
  • Validate input client-side before submitting
  • Provide user-friendly error messages