Error Handling

Comprehensive guide to understanding and handling errors in the MegaVault API, including error codes, formats, and troubleshooting strategies.

Error Handling Overview

MegaVault API uses standard HTTP status codes and provides detailed error information to help developers handle errors gracefully and provide meaningful feedback to users.

Consistent Format

Standardized error responses

  • ✅ Consistent JSON structure
  • ✅ Detailed error messages
  • ✅ Contextual information
  • ✅ Actionable guidance

Error Categories

Organized error types

  • ✅ Client errors (4xx)
  • ✅ Server errors (5xx)
  • ✅ Validation errors
  • ✅ Authentication errors

Developer Tools

Debugging assistance

  • ✅ Error documentation
  • ✅ Debug information
  • ✅ Request tracing
  • ✅ Support resources
💡

Error Handling Philosophy

All API errors provide enough information for developers to understand what went wrong and how to fix it, while being safe to display to end users when appropriate.

Error Response Format

All error responses follow a consistent JSON structure with detailed information.

Standard Error Response

Error Response Structure
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "type": "client_error",
    "timestamp": "2024-01-20T15:30:00Z",
    "requestId": "req_abc123def456",
    "details": {
      "field": "email",
      "value": "invalid-email",
      "constraint": "Valid email format required"
    }
  },
  "meta": {
    "documentation": "https://docs.megavault.com/api/errors#ERROR_CODE",
    "support": "https://support.megavault.com"
  }
}

Error Response Fields

FieldTypeDescription
successbooleanAlways false for error responses
error.codestringMachine-readable error identifier
error.messagestringHuman-readable error description
error.typestringError category (client_error, server_error, etc.)
error.detailsobjectAdditional context-specific information
requestIdstringUnique request identifier for debugging

HTTP Status Codes

MegaVault API uses standard HTTP status codes to indicate the outcome of requests.

Success Codes (2xx)

200 OK

Request successful, data returned

  • GET requests with data
  • PUT requests with updated data
  • DELETE requests with confirmation

201 Created

Resource created successfully

  • POST requests creating new resources
  • File uploads
  • User registration

Client Error Codes (4xx)

CodeStatusDescriptionCommon Causes
400Bad RequestInvalid request format or parametersMalformed JSON, missing required fields
401UnauthorizedAuthentication required or invalidMissing/expired token, invalid credentials
403ForbiddenInsufficient permissionsAccess denied, quota exceeded
404Not FoundResource does not existInvalid file ID, deleted resource
409ConflictResource conflictDuplicate file name, concurrent modification
413Payload Too LargeFile or request too largeFile exceeds size limit
429Too Many RequestsRate limit exceededToo many API calls, implement backoff

Server Error Codes (5xx)

500 Internal Server Error

Unexpected server error occurred

  • Database connection issues
  • Unhandled exceptions
  • Configuration problems

503 Service Unavailable

Service temporarily unavailable

  • Maintenance mode
  • Overloaded servers
  • External service dependencies

Application Error Codes

Detailed application-specific error codes for precise error handling.

Authentication Errors

Authentication Error Examples
// Invalid credentials
{
  "success": false,
  "error": {
    "code": "INVALID_CREDENTIALS",
    "message": "Invalid email or password",
    "type": "authentication_error"
  }
}

// Token expired
{
  "success": false,
  "error": {
    "code": "TOKEN_EXPIRED",
    "message": "Authentication token has expired",
    "type": "authentication_error",
    "details": {
      "expiredAt": "2024-01-20T14:30:00Z",
      "refreshRequired": true
    }
  }
}

// Account suspended
{
  "success": false,
  "error": {
    "code": "ACCOUNT_SUSPENDED",
    "message": "Account has been suspended due to policy violation",
    "type": "authentication_error",
    "details": {
      "reason": "terms_violation",
      "suspendedAt": "2024-01-15T10:00:00Z",
      "appealUrl": "https://support.megavault.com/appeal"
    }
  }
}

File Operation Errors

File Error Examples
// File not found
{
  "success": false,
  "error": {
    "code": "FILE_NOT_FOUND",
    "message": "The requested file could not be found",
    "type": "client_error",
    "details": {
      "fileId": "file_123456789",
      "possibleCauses": ["File was deleted", "Invalid file ID", "Access denied"]
    }
  }
}

// Storage quota exceeded
{
  "success": false,
  "error": {
    "code": "STORAGE_QUOTA_EXCEEDED",
    "message": "Upload would exceed your storage quota",
    "type": "client_error",
    "details": {
      "currentUsage": 5368709120,
      "storageLimit": 5368709120,
      "fileSize": 1048576,
      "upgradeUrl": "https://megavault.com/upgrade"
    }
  }
}

// Unsupported file type
{
  "success": false,
  "error": {
    "code": "UNSUPPORTED_FILE_TYPE",
    "message": "File type not supported",
    "type": "client_error",
    "details": {
      "fileType": "exe",
      "supportedTypes": ["jpg", "png", "pdf", "docx", "txt"]
    }
  }
}

Validation Errors

Detailed validation errors with field-specific information.

Validation Error Example
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "type": "client_error",
    "details": {
      "fields": [
        {
          "field": "email",
          "value": "invalid-email",
          "errors": [
            {
              "code": "INVALID_FORMAT",
              "message": "Must be a valid email address"
            }
          ]
        },
        {
          "field": "password",
          "value": "[REDACTED]",
          "errors": [
            {
              "code": "TOO_SHORT",
              "message": "Password must be at least 8 characters long"
            },
            {
              "code": "MISSING_UPPERCASE",
              "message": "Password must contain at least one uppercase letter"
            }
          ]
        }
      ]
    }
  }
}

Common Validation Rules

RuleCodeDescription
RequiredREQUIREDField is required and cannot be empty
Email FormatINVALID_FORMATMust be a valid email address
String LengthTOO_SHORT/TOO_LONGString length validation
Unique ValueNOT_UNIQUEValue must be unique

Best Practices

Recommended approaches for handling errors in your applications.

Error Handling Strategy

JavaScript Error Handling
class MegaVaultAPIError extends Error {
  constructor(response, requestId) {
    super(response.error.message);
    this.name = 'MegaVaultAPIError';
    this.code = response.error.code;
    this.type = response.error.type;
    this.details = response.error.details;
    this.requestId = requestId;
    this.statusCode = response.status;
  }
}

async function apiCall(endpoint, options = {}) {
  try {
    const response = await fetch(endpoint, options);
    const data = await response.json();
    
    if (!response.ok || !data.success) {
      throw new MegaVaultAPIError(data, response.headers.get('X-Request-ID'));
    }
    
    return data;
  } catch (error) {
    if (error instanceof MegaVaultAPIError) {
      handleAPIError(error);
    } else {
      handleNetworkError(error);
    }
    throw error;
  }
}

function handleAPIError(error) {
  switch (error.code) {
    case 'TOKEN_EXPIRED':
      // Refresh token and retry
      return refreshTokenAndRetry();
    
    case 'STORAGE_QUOTA_EXCEEDED':
      // Show upgrade prompt
      showUpgradeDialog(error.details.upgradeUrl);
      break;
    
    case 'VALIDATION_ERROR':
      // Show field-specific errors
      displayValidationErrors(error.details.fields);
      break;
    
    case 'RATE_LIMIT_EXCEEDED':
      // Implement exponential backoff
      const retryAfter = error.details.retryAfter || 60;
      scheduleRetry(retryAfter);
      break;
    
    default:
      // Generic error handling
      showErrorMessage(error.message);
  }
}

Retry Logic

Retry Implementation
async function retryableRequest(endpoint, options, maxRetries = 3) {
  let lastError;
  
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall(endpoint, options);
    } catch (error) {
      lastError = error;
      
      // Don't retry client errors (4xx) except 429
      if (error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
        throw error;
      }
      
      // Calculate exponential backoff delay
      const delay = Math.min(1000 * Math.pow(2, attempt - 1), 30000);
      
      if (attempt < maxRetries) {
        console.log(`Request failed, retrying in ${delay}ms (attempt ${attempt}/${maxRetries})`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }
  
  throw lastError;
}

User-Friendly Messages

  • Translate Technical Errors: Convert API error codes to user-friendly messages
  • Provide Context: Explain what the user can do to resolve the issue
  • Offer Solutions: Include links to help, upgrade pages, or support
  • Log Details: Log technical details for debugging while showing simple messages to users

Common Issues

Solutions to frequently encountered problems and error scenarios.

Authentication Issues

Token Expired

Problem: API returns 401 with TOKEN_EXPIRED

Solution:

  • Use refresh token to get new access token
  • Implement automatic token refresh
  • Handle refresh failures gracefully

Invalid Credentials

Problem: Login fails with INVALID_CREDENTIALS

Solution:

  • Verify email and password are correct
  • Check for typos or case sensitivity
  • Implement password reset flow

File Upload Issues

File Too Large

Problem: Upload fails with FILE_TOO_LARGE

Solution:

  • Check file size against plan limits
  • Implement chunked uploads for large files
  • Compress files before upload

Network Timeout

Problem: Upload times out on large files

Solution:

  • Increase request timeout
  • Use resumable uploads
  • Show progress indicators

Rate Limiting

Rate Limit Handling
function handleRateLimit(error) {
  const retryAfter = error.details.retryAfter || 60;
  const resetTime = new Date(Date.now() + retryAfter * 1000);
  
  console.log(`Rate limited. Retry after: ${resetTime.toISOString()}`);
  
  // Show user-friendly message
  showToast(`Too many requests. Please wait ${retryAfter} seconds.`);
  
  // Schedule retry
  setTimeout(() => {
    // Retry the failed request
    retryFailedRequest();
  }, retryAfter * 1000);
}
⚠️

Request ID for Support

Always include the requestId from error responses when contacting support. This helps identify and troubleshoot specific issues quickly.