LeafMove Documentation CenterLeafMove Documentation Center
Home
Guide
API Docs
LeafMove Official
  • 简体中文
  • English
GitHub
Home
Guide
API Docs
LeafMove Official
  • 简体中文
  • English
GitHub
  • 🔧 API Docs

    • API Documentation
    • API Authentication Guide
    • API Usage Examples
    • Error Codes Reference

Error Codes Reference

Complete reference of all error codes that the API may return, including their meanings and solutions.

📋 Error Response Format

All error responses follow a consistent format:

{
  "code": 400,
  "message": "Bad Request",
  "data": null,
  "errors": [
    {
      "field": "email",
      "message": "Invalid email format"
    }
  ],
  "timestamp": "2024-01-01T00:00:00Z",
  "path": "/api/documents"
}

🔢 HTTP Status Codes

2xx Success Status Codes

Status CodeMeaningDescription
200OKRequest successful
201CreatedResource created successfully
202AcceptedRequest accepted, processing
204No ContentRequest successful, no content returned

4xx Client Errors

Status CodeMeaningCommon CausesSolutions
400Bad RequestInvalid request parametersCheck request parameter format and required fields
401UnauthorizedUnauthorized accessCheck if API token is valid
403ForbiddenInsufficient permissionsConfirm user permissions or contact administrator
404Not FoundResource not foundCheck resource ID or path
405Method Not AllowedRequest method not allowedUse correct HTTP method
409ConflictResource conflictCheck if resource already exists
422Unprocessable EntityData validation failedCheck data format and validation rules
429Too Many RequestsRate limit exceededReduce request frequency or wait

5xx Server Errors

Status CodeMeaningCommon CausesSolutions
500Internal Server ErrorServer internal errorContact technical support
502Bad GatewayGateway errorRetry later or contact technical support
503Service UnavailableService unavailableRetry later
504Gateway TimeoutGateway timeoutRetry later

🔍 Business Error Codes

User-Related Errors (1000-1999)

Error CodeError MessageDescriptionSolution
1001User not foundSpecified user ID does not existCheck if user ID is correct
1002Email already existsEmail already in use during registrationUse different email or recover password
1003Invalid passwordLogin password incorrectCheck password or reset password
1004User disabledUser account disabled by administratorContact administrator to enable
1005Invalid email formatEmail address format incorrectUse correct email format
1006Password too weakPassword does not meet security requirementsUse stronger password

Authentication-Related Errors (2000-2999)

Error CodeError MessageDescriptionSolution
2001Invalid tokenAPI token format error or expiredGet new valid token
2002Token expiredAPI token has exceeded validity periodRefresh token or re-login
2003Insufficient permissionsCurrent user has insufficient permissionsContact administrator for permission upgrade
2004Too many login attemptsToo many login failures in short timeWait and retry later
2005Invalid verification codeEntered verification code incorrectGet new verification code
2006Verification code expiredVerification code has exceeded validity periodGet new verification code

Data-Related Errors (3000-3999)

Error CodeError MessageDescriptionSolution
3001Data not foundRequested data record does not existCheck if data ID is correct
3002Data already existsData being created already existsUse update operation or check uniqueness
3003Invalid data formatSubmitted data format incorrectCheck data format and type
3004Missing required fieldMissing required fieldsProvide all required fields
3005Field length exceededField value exceeds maximum lengthShorten field value length
3006Data relationship errorRelated data does not exist or invalidCheck validity of related data

System-Related Errors (4000-4999)

Error CodeError MessageDescriptionSolution
4001System maintenanceSystem under maintenanceWait for maintenance completion
4002Service unavailableService temporarily unavailableRetry later
4003Request timeoutRequest processing timeoutRetry later or optimize request
4004Storage fullServer storage space insufficientContact technical support
4005Configuration errorSystem configuration errorContact technical support

Business Logic Errors (5000-5999)

Error CodeError MessageDescriptionSolution
5001Operation not allowedOperation not allowed in current stateCheck business state
5002Insufficient balanceAccount balance insufficientTop up or check balance
5003Insufficient inventoryProduct inventory insufficientChoose other products or wait for restock
5004Invalid order statusOrder status does not allow this operationCheck order status
5005Time restrictionOperation exceeds time limitOperate within allowed time

🛠 Error Handling Examples

JavaScript Error Handling

async function handleAPIError(response) {
  if (!response.ok) {
    const errorData = await response.json();
    
    switch (response.status) {
      case 400:
        console.error('Bad request:', errorData.message);
        // Display specific field errors
        if (errorData.errors) {
          errorData.errors.forEach(error => {
            console.error(`Field ${error.field}: ${error.message}`);
          });
        }
        break;
        
      case 401:
        console.error('Authentication failed:', errorData.message);
        // Redirect to login page
        window.location.href = '/login';
        break;
        
      case 403:
        console.error('Insufficient permissions:', errorData.message);
        // Show permission denied message
        alert('You do not have permission to perform this action');
        break;
        
      case 404:
        console.error('Resource not found:', errorData.message);
        break;
        
      case 429:
        console.error('Too many requests:', errorData.message);
        // Implement backoff retry
        setTimeout(() => {
          // Retry request
        }, 5000);
        break;
        
      case 500:
        console.error('Server error:', errorData.message);
        // Show friendly error message
        alert('Server temporarily experiencing issues, please try again later');
        break;
        
      default:
        console.error('Unknown error:', errorData.message);
    }
    
    throw new APIError(response.status, errorData.message, errorData);
  }
  
  return response.json();
}

// Custom error class
class APIError extends Error {
  constructor(status, message, data) {
    super(message);
    this.name = 'APIError';
    this.status = status;
    this.data = data;
  }
}

Python Error Handling

import requests
from requests.exceptions import RequestException

class APIError(Exception):
    def __init__(self, status_code, message, data=None):
        self.status_code = status_code
        self.message = message
        self.data = data
        super().__init__(self.message)

def handle_api_response(response):
    """Handle API response and errors"""
    try:
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError:
        error_data = response.json()
        
        if response.status_code == 400:
            print(f"Bad request: {error_data['message']}")
        elif response.status_code == 401:
            print(f"Authentication failed: {error_data['message']}")
            # Re-acquire token
        elif response.status_code == 403:
            print(f"Insufficient permissions: {error_data['message']}")
        elif response.status_code == 404:
            print(f"Resource not found: {error_data['message']}")
        elif response.status_code == 429:
            print(f"Too many requests: {error_data['message']}")
            # Implement retry logic
        elif response.status_code >= 500:
            print(f"Server error: {error_data['message']}")
        
        raise APIError(
            response.status_code, 
            error_data['message'], 
            error_data
        )
    except RequestException as e:
        print(f"Network request failed: {e}")
        raise

🔧 Debugging Tips

1. Enable Detailed Error Information

In development environment, you can request more detailed error information:

const response = await fetch('/api/documents', {
  headers: {
    'Authorization': 'Bearer ' + token,
    'X-Debug': 'true'  // Enable debug mode
  }
});

2. Error Logging

function logError(error, context) {
  const errorLog = {
    timestamp: new Date().toISOString(),
    error: {
      status: error.status,
      message: error.message,
      data: error.data
    },
    context: context,
    userAgent: navigator.userAgent,
    url: window.location.href
  };
  
  // Send to logging service
  console.error('API Error:', errorLog);
  
  // Optional: Send to error monitoring service
  // sendToErrorMonitoring(errorLog);
}

3. Retry Mechanism

async function retryRequest(requestFn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await requestFn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // Don't retry for certain error codes
      if ([400, 401, 403, 404].includes(error.status)) {
        throw error;
      }
      
      // Exponential backoff
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

📞 Getting Help

If you encounter error codes not listed in this documentation or need technical support, please:

  1. Record complete error information
  2. Provide detailed request information (URL, parameters, headers, etc.)
  3. Contact us through the following channels:
    • Technical support email: support@leafmove.com
    • Online customer service: https://leafmove.com/support
    • GitHub Issues: https://github.com/leafmove/autodoc/issues

🔗 Related Resources

  • API Overview
  • Authentication Guide
  • Usage Examples
Edit this page on GitHub
Prev
API Usage Examples