Skip to main content

Error Response Format

All API errors follow a consistent JSON structure that makes it easy to parse and handle errors programmatically.

Standard Error Response

{
  "meta": {
    "code": 88,
    "message": "Invalid Parameter",
    "description": "The product_id parameter is required"
  }
}

Response Fields

FieldTypeDescription
meta.codeintegerInternal error code for categorizing errors
meta.messagestringHuman-readable error title
meta.descriptionstringDetailed error description (optional)

HTTP Status Codes

The API uses standard HTTP status codes to indicate the type of error:

200 OK

Request succeeded

400 Bad Request

Invalid request parameters or malformed request body

401 Unauthorized

Missing or invalid authentication token

404 Not Found

Resource not found or endpoint doesn’t exist

500 Internal Server Error

Server error or unexpected exception

Error Codes

The API uses internal error codes in addition to HTTP status codes for more granular error handling:

Common Error Codes

errors.py
OK = {
    'status': falcon.HTTP_200,
    'code': 200,
}

ERR_UNKNOWN = {
    'status': falcon.HTTP_500,
    'code': 500,
    'title': 'Unknown Error'
}

ERR_AUTH_REQUIRED = {
    'status': falcon.HTTP_401,
    'code': 99,
    'title': 'Authentication Required'
}

ERR_INVALID_PARAMETER = {
    'status': falcon.HTTP_400,
    'code': 88,
    'title': 'Invalid Parameter'
}

ERR_DATABASE_ROLLBACK = {
    'status': falcon.HTTP_500,
    'code': 77,
    'title': 'Database Rollback Error'
}

ERR_NOT_SUPPORTED = {
    'status': falcon.HTTP_404,
    'code': 10,
    'title': 'Not Supported'
}

ERR_USER_NOT_EXISTS = {
    'status': falcon.HTTP_404,
    'code': 21,
    'title': 'User Not Exists'
}

ERR_PASSWORD_NOT_MATCH = {
    'status': falcon.HTTP_400,
    'code': 22,
    'title': 'Password Not Match'
}

Error Code Reference

CodeHTTP StatusError TypeDescription
200200OKRequest completed successfully
10404Not SupportedMethod or endpoint not supported
21404User Not ExistsUser account not found
22400Password Not MatchInvalid password provided
77500Database RollbackDatabase transaction failed
88400Invalid ParameterRequest parameter validation failed
99401Auth RequiredAuthentication token required or invalid
500500Unknown ErrorUnexpected server error
Always check both the HTTP status code and the internal error code for comprehensive error handling.

Error Classes

The API defines custom exception classes for different error scenarios:

AppError (Base Class)

class AppError(Exception):
    def __init__(self, error=ERR_UNKNOWN, description=None):
        self.error = error
        self.error['description'] = description

    @property
    def code(self):
        return self.error['code']

    @property
    def status(self):
        return self.error['status']

InvalidParameterError

Raised when request parameters fail validation:
class InvalidParameterError(AppError):
    def __init__(self, description=None):
        super().__init__(ERR_INVALID_PARAMETER)
        self.error['description'] = description
Example Response:
{
  "meta": {
    "code": 88,
    "message": "Invalid Parameter",
    "description": "quantity must be greater than 0"
  }
}

UnauthorizedError

Raised for authentication and authorization failures:
class UnauthorizedError(AppError):
    def __init__(self, description=None):
        super().__init__(ERR_AUTH_REQUIRED)
        self.error['description'] = description
Example Response:
{
  "meta": {
    "code": 99,
    "message": "Authentication Required",
    "description": "Your session has expired. Kindly logout and login"
  }
}

UserNotExistsError

Raised when a user account cannot be found:
class UserNotExistsError(AppError):
    def __init__(self, description=None):
        super().__init__(ERR_USER_NOT_EXISTS)
        self.error['description'] = description

DatabaseError

Raised for database operation failures:
class DatabaseError(AppError):
    def __init__(self, error, args=None, params=None):
        super().__init__(error)
        obj = OrderedDict()
        obj['details'] = ', '.join(args)
        obj['params'] = str(params)
        self.error['description'] = obj

NotSupportedError

Raised when an endpoint or method is not supported:
class NotSupportedError(AppError):
    def __init__(self, method=None, url=None):
        super().__init__(ERR_NOT_SUPPORTED)
        if method and url:
            self.error['description'] = f'method: {method}, url: {url}'

Common Error Scenarios

Authentication Errors

HTTP Status: 401 Unauthorized
Error Code: 99
{
  "meta": {
    "code": 99,
    "message": "Authentication Required",
    "description": "Your session has expired. Kindly logout and login"
  }
}
How to Handle:
  • Clear local authentication token
  • Redirect user to login page
  • Implement token refresh mechanism
HTTP Status: 401 Unauthorized
Error Code: 99
{
  "meta": {
    "code": 99,
    "message": "Authentication Required",
    "description": "Your Account has been blocked, Please contact thesouledstore Team"
  }
}
How to Handle:
  • Display customer support contact information
  • Log out the user immediately
  • Prevent further API requests
HTTP Status: 401 Unauthorized
Error Code: 99
Occurs when:
  • User has 2FA enabled but provides a non-2FA token (or vice versa)
  • Token prefix “2f.” doesn’t match user’s 2FA status
{
  "meta": {
    "code": 99,
    "message": "Authentication Required",
    "description": "Your session has expired. Kindly logout and login"
  }
}

Validation Errors

HTTP Status: 400 Bad Request
Error Code: 88
{
  "meta": {
    "code": 88,
    "message": "Invalid Parameter",
    "description": "product_id is required"
  }
}
How to Handle:
  • Validate request parameters before sending
  • Display field-specific error messages to users
  • Check API documentation for required fields
HTTP Status: 400 Bad Request
Error Code: 88
{
  "meta": {
    "code": 88,
    "message": "Invalid Parameter",
    "description": "quantity must be a positive integer"
  }
}

Resource Errors

HTTP Status: 404 Not Found
Error Code: 21
{
  "meta": {
    "code": 21,
    "message": "User Not Exists",
    "description": "No account found with this email"
  }
}
HTTP Status: 404 Not Found
Error Code: 10
{
  "meta": {
    "code": 10,
    "message": "Not Supported",
    "description": "method: DELETE, url: /api/v2/product/123"
  }
}

Server Errors

HTTP Status: 500 Internal Server Error
Error Code: 77
{
  "meta": {
    "code": 77,
    "message": "Database Rollback Error",
    "description": {
      "details": "Connection timeout",
      "params": "{'user_id': 12345}"
    }
  }
}
How to Handle:
  • Implement retry logic with exponential backoff
  • Log error details for debugging
  • Display generic error message to users
HTTP Status: 500 Internal Server Error
Error Code: 500
{
  "meta": {
    "code": 500,
    "message": "Unknown Error"
  }
}
How to Handle:
  • Retry the request once
  • Log the full request/response for investigation
  • Contact API support if error persists

Best Practices

1. Check HTTP Status First

Always check the HTTP status code before parsing the response body:
if (response.status !== 200) {
  const error = await response.json();
  handleError(error.meta);
}

2. Handle Authentication Errors Globally

Implement a global handler for 401 errors:
if (error.meta.code === 99) {
  // Clear auth token
  localStorage.removeItem('authToken');
  // Redirect to login
  window.location.href = '/login';
}

3. Implement Retry Logic

Retry failed requests with exponential backoff:
async function apiRequestWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 500 && i < maxRetries - 1) {
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }
      return response;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

4. Display User-Friendly Messages

Map technical errors to user-friendly messages:
const ERROR_MESSAGES = {
  99: 'Your session has expired. Please log in again.',
  88: 'Please check your input and try again.',
  500: 'Something went wrong. Please try again later.'
};

function getUserMessage(errorCode) {
  return ERROR_MESSAGES[errorCode] || 'An unexpected error occurred.';
}

5. Log Errors for Debugging

Always log error details in development:
if (process.env.NODE_ENV === 'development') {
  console.error('API Error:', {
    code: error.meta.code,
    message: error.meta.message,
    description: error.meta.description,
    endpoint: url,
    timestamp: new Date().toISOString()
  });
}
The API includes detailed error descriptions to help with debugging. Always check the description field for additional context.

Error Handling in Production

The API includes a global error handler that catches unhandled exceptions:
main.py
from middleware.LoggingMiddleware import logging_error_handler

app.add_error_handler(Exception, logging_error_handler)
This ensures that:
  • All exceptions are logged for monitoring
  • Sensitive information is not exposed to clients
  • Consistent error format is maintained
  • Database connections are properly cleaned up

Contact Support

If you encounter persistent errors or need assistance:
  • Check the API documentation for correct usage
  • Review your request parameters and authentication
  • Contact technical support with error codes and timestamps

Build docs developers (and LLMs) love