Error Handling Guide

Hướng dẫn xử lý lỗi và HTTP status codes trong Vietnam Medical AI APIs

HTTP Status Codes

Tất cả API endpoints trả về các HTTP status codes chuẩn:

Status Code Meaning Description When It Happens
200 OK Success Request thành công API xử lý request và trả về kết quả
400 Bad Request Client Error Request không hợp lệ Thiếu parameters, format sai, file không đúng
401 Unauthorized Authentication Required Chưa xác thực Không có API token hoặc token không hợp lệ
403 Forbidden Access Denied Không có quyền truy cập Token hết hạn, revoked, hoặc không có quyền cho service này
404 Not Found Resource Not Found Không tìm thấy endpoint URL sai hoặc resource không tồn tại
429 Too Many Requests Rate Limit Exceeded Vượt quá rate limit Gửi quá nhiều requests trong thời gian ngắn
500 Internal Server Error Server Error Lỗi server Lỗi xử lý nội bộ, model error, GPU out of memory

Error Response Format

Tất cả error responses đều theo format JSON chuẩn:

Standard Error Response

{
  "success": false,
  "error": "Error message describing what went wrong",
  "code": "ERROR_CODE",
  "details": {
    // Additional error details (optional)
  }
}

Examples By Status Code

400 Bad Request

{
  "success": false,
  "error": "Missing required parameter: audio_file",
  "code": "MISSING_PARAMETER"
}

401 Unauthorized

{
  "success": false,
  "error": "No API token provided",
  "message": "Please provide an API key in Authorization header"
}

403 Forbidden

{
  "success": false,
  "error": "Service not allowed for this token",
  "message": "Token validation failed"
}

429 Rate Limit Exceeded

{
  "success": false,
  "error": "Rate limit exceeded",
  "rate_limit": {
    "current": 61,
    "limit": 60,
    "remaining": 0,
    "reset_at": "2025-11-27T10:30:00Z"
  }
}

500 Internal Server Error

{
  "success": false,
  "error": "Internal server error",
  "message": "Model inference failed",
  "details": {
    "error_type": "CUDA_OUT_OF_MEMORY",
    "suggestion": "Try with a smaller file or retry later"
  }
}

Best Practices

1. Always Check Response Status

import requests

response = requests.post(url, headers=headers, files=files)

if response.status_code == 200:
    result = response.json()
    print("Success:", result)
elif response.status_code == 401:
    print("Authentication failed - check your API token")
elif response.status_code == 429:
    print("Rate limit exceeded - wait and retry")
else:
    print(f"Error {response.status_code}: {response.text}")

2. Implement Retry Logic

import time
from requests.exceptions import RequestException

def api_call_with_retry(url, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(url, headers=headers, files=files)
            
            if response.status_code == 429:
                # Rate limited - exponential backoff
                wait_time = 2 ** attempt
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
                continue
            
            if response.status_code >= 500:
                # Server error - retry
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)
                    continue
            
            return response
            
        except RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)
    
    return None

3. Handle Rate Limits Gracefully

import time

response = requests.post(url, headers=headers, files=files)

if response.status_code == 429:
    # Check for Retry-After header
    retry_after = int(response.headers.get('Retry-After', 60))
    print(f"Rate limited. Waiting {retry_after} seconds...")
    time.sleep(retry_after)
    
    # Retry the request
    response = requests.post(url, headers=headers, files=files)

4. Log Errors for Debugging

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    response = requests.post(url, headers=headers, files=files)
    response.raise_for_status()
    
except requests.exceptions.HTTPError as e:
    logger.error(f"HTTP Error: {e}")
    logger.error(f"Response: {e.response.text}")
    
except requests.exceptions.RequestException as e:
    logger.error(f"Request failed: {e}")

5. Use Try-Except Blocks

try:
    response = requests.post(url, headers=headers, files=files, timeout=30)
    response.raise_for_status()
    result = response.json()
    
except requests.exceptions.Timeout:
    print("Request timeout - server is slow or unresponsive")
    
except requests.exceptions.ConnectionError:
    print("Connection error - check network or server status")
    
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e.response.status_code}")
    error_data = e.response.json()
    print(f"Error message: {error_data.get('error')}")
    
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

Service-Specific Errors

Medical Transcribe

{
  "success": false,
  "error": "Audio file too large",
  "details": {
    "max_size": "100MB",
    "received_size": "150MB"
  }
}

{
  "success": false,
  "error": "Unsupported audio format",
  "details": {
    "supported_formats": ["wav", "mp3", "m4a", "flac"],
    "received_format": "webm"
  }
}

Face Recognition

{
  "success": false,
  "error": "No faces detected in image",
  "details": {
    "suggestion": "Ensure image contains clear, front-facing faces"
  }
}

{
  "success": false,
  "error": "Image quality too low",
  "details": {
    "min_resolution": "640x480",
    "received_resolution": "320x240"
  }
}

DeepSeek OCR

{
  "success": false,
  "error": "No text detected in image",
  "details": {
    "suggestion": "Ensure image is clear and contains readable text"
  }
}

Debugging Tips

Quick Checklist

  • ✓ Check API token is valid and not expired
  • ✓ Verify token has permission for the service
  • ✓ Ensure request format matches API documentation
  • ✓ Check file size and format requirements
  • ✓ Monitor rate limits in response headers
  • ✓ Check server status at https://pnt.badt.vn/
  • ✓ Review centralized logs for detailed errors

Common Issues & Solutions

Issue: "No API token provided"

Solution: Add Authorization header: Authorization: Bearer YOUR_TOKEN

Issue: "Rate limit exceeded"

Solution: Wait 60 seconds or implement request throttling. Check your rate limit in admin panel.

Issue: "Token validation failed"

Solution: Token might be expired, revoked, or doesn't have access to this service. Contact admin.

Issue: "Internal server error"

Solution: GPU might be out of memory or model crashed. Check system status and retry. If persists, contact admin.

Need Help?

Nếu bạn gặp vấn đề không giải quyết được:

  • Kiểm tra System Status
  • Xem Code Examples để tham khảo
  • Liên hệ admin: thanhliem.vo@gmail.com
  • Kiểm tra logs tại admin dashboard