Skip to main content
VK-IO provides a comprehensive error system with specific error classes for different failure scenarios. All errors extend from the base VKError class.

VKError

Base error class for all VK-IO errors.
import { VKError } from 'vk-io';

try {
  // Some operation
} catch (error) {
  if (error instanceof VKError) {
    console.error(`Error ${error.code}: ${error.message}`);
  }
}

Properties

code
string | number
required
Error code identifier.
message
string
required
Human-readable error message.
stack
string
Stack trace of the error.
cause
Error
Original error that caused this error (if applicable).

Constructor

options
object
required
Error configuration object.

APIError

Thrown when VK API returns an error response.
import { APIError, APIErrorCode } from 'vk-io';

try {
  await vk.api.messages.send({
    peer_id: 123,
    message: 'Hello!',
    random_id: 0
  });
} catch (error) {
  if (error instanceof APIError) {
    console.log(`API Error ${error.code}: ${error.message}`);
    
    if (error.code === APIErrorCode.CAPTCHA) {
      console.log('Captcha required:', error.captchaImg);
    }
  }
}

Properties

code
number
required
VK API error code (see APIErrorCode enum).
message
string
required
Error message in format: Code №{code} - {error_msg}.
params
IAPIErrorParam[]
required
Request parameters that were sent.
captchaSid
string
Captcha session ID (when code is 14).
captchaImg
string
URL to captcha image (when code is 14).
redirectUri
string
Redirect URI for validation (when code is 17) or captcha.
confirmationText
string
Text that needs confirmation (when code is 24).

ExecuteError

Thrown when an error occurs within VK’s execute method.
import { ExecuteError } from 'vk-io';

const chain = vk.api.chain();
chain.append('users.get', { user_ids: 1 });
chain.append('invalid.method', {});

try {
  await chain.run();
} catch (error) {
  if (error instanceof ExecuteError) {
    console.log('Method failed:', error.method);
    console.log('Error code:', error.code);
  }
}

Properties

method
string
required
The API method that failed during execution.
code
number
required
VK API error code.
message
string
required
Error message.

CollectError

Thrown when collect iterator encounters errors.
import { CollectError, CollectErrorCode } from 'vk-io';
import { createCollectIterator } from 'vk-io';

try {
  const iterator = createCollectIterator({
    api: vk.api,
    method: 'wall.get',
    params: { owner_id: 1 },
    countPerRequest: 100
  });
  
  for await (const data of iterator) {
    // Process data
  }
} catch (error) {
  if (error instanceof CollectError) {
    console.log('Collect error:', error.code);
    console.log('Execute errors:', error.errors);
  }
}

Properties

code
string
required
Error code (typically 'EXECUTE_ERROR').
message
string
required
Error message.
errors
ExecuteError[]
required
Array of errors that occurred during execute batch.

UploadError

Thrown when file upload fails.
import { UploadError, UploadErrorCode } from 'vk-io';

try {
  await vk.upload.messagePhoto({
    peer_id: 123,
    source: './invalid-file.jpg'
  });
} catch (error) {
  if (error instanceof UploadError) {
    switch (error.code) {
      case UploadErrorCode.MISSING_PARAMETERS:
        console.log('Missing required parameters');
        break;
      case UploadErrorCode.NO_FILES_TO_UPLOAD:
        console.log('No files provided');
        break;
      case UploadErrorCode.EXCEEDED_MAX_FILES:
        console.log('Too many files');
        break;
      case UploadErrorCode.UNSUPPORTED_SOURCE_TYPE:
        console.log('Invalid file source');
        break;
    }
  }
}

Error Codes

  • MISSING_PARAMETERS - Required parameters not provided
  • NO_FILES_TO_UPLOAD - No files in upload request
  • EXCEEDED_MAX_FILES - Too many files for this upload type
  • UNSUPPORTED_SOURCE_TYPE - Invalid source type

UpdatesError

Thrown when updates polling or webhook handling fails.
import { UpdatesError, UpdatesErrorCode } from 'vk-io';

vk.updates.on('error', (error) => {
  if (error instanceof UpdatesError) {
    if (error.code === UpdatesErrorCode.NEED_RESTART) {
      console.log('Updates need restart');
      vk.updates.start().catch(console.error);
    } else if (error.code === UpdatesErrorCode.POLLING_REQUEST_FAILED) {
      console.log('Polling request failed');
    }
  }
});

Error Codes

  • NEED_RESTART - Updates service needs to be restarted
  • POLLING_REQUEST_FAILED - Long polling request failed

ResourceError

Thrown when parsing VK resource URLs fails.
import { ResourceError, ResourceErrorCode } from 'vk-io';
import { resolveResource } from 'vk-io';

try {
  const resource = await resolveResource({
    api: vk.api,
    resource: 'https://vk.com/invalid_url'
  });
} catch (error) {
  if (error instanceof ResourceError) {
    switch (error.code) {
      case ResourceErrorCode.INVALID_URL:
        console.log('Invalid VK URL');
        break;
      case ResourceErrorCode.INVALID_RESOURCE:
        console.log('Invalid resource type');
        break;
      case ResourceErrorCode.RESOURCE_NOT_FOUND:
        console.log('Resource not found');
        break;
    }
  }
}

Error Codes

  • INVALID_URL - URL format is invalid
  • INVALID_RESOURCE - Resource type is not recognized
  • RESOURCE_NOT_FOUND - Resource does not exist

API Error Codes

Common VK API error codes (from APIErrorCode enum):

Authentication Errors

APIErrorCode.AUTH
// User authorization failed

Rate Limiting

APIErrorCode.TOO_MANY
// Too many requests per second

Captcha & Security

APIErrorCode.CAPTCHA
// Captcha verification required
// Check error.captchaSid and error.captchaImg

Permission Errors

APIErrorCode.ACCESS
// Access denied to resource

Parameter Errors

APIErrorCode.PARAM
// One of parameters is invalid

Message Errors

APIErrorCode.MESSAGES_USER_BLOCKED
// Can't send message - user in blacklist

Error Handling Patterns

Handle Specific API Errors

import { APIError, APIErrorCode } from 'vk-io';

const sendMessage = async (peerId: number, message: string) => {
  try {
    return await vk.api.messages.send({
      peer_id: peerId,
      message,
      random_id: 0
    });
  } catch (error) {
    if (error instanceof APIError) {
      switch (error.code) {
        case APIErrorCode.MESSAGES_USER_BLOCKED:
          console.log('User blocked bot');
          break;
        case APIErrorCode.MESSAGES_PRIVACY:
          console.log('Privacy settings prevent messaging');
          break;
        case APIErrorCode.CAPTCHA:
          console.log('Captcha required:', error.captchaImg);
          // Handle captcha
          break;
        default:
          console.error('API Error:', error.message);
      }
    }
    throw error;
  }
};

Retry with Exponential Backoff

import { APIError, APIErrorCode } from 'vk-io';
import { delay } from 'vk-io';

const retryableErrors = [
  APIErrorCode.TOO_MANY,
  APIErrorCode.FLOOD,
  APIErrorCode.RATE_LIMIT
];

const callWithRetry = async (fn: () => Promise<any>, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error instanceof APIError && retryableErrors.includes(error.code)) {
        if (i < maxRetries - 1) {
          const delayMs = 1000 * Math.pow(2, i);
          console.log(`Rate limited, retrying in ${delayMs}ms...`);
          await delay(delayMs);
          continue;
        }
      }
      throw error;
    }
  }
};

const users = await callWithRetry(() => 
  vk.api.users.get({ user_ids: [1, 2, 3] })
);

Global Error Handler

import { VKError, APIError, UploadError, UpdatesError } from 'vk-io';

const handleError = (error: unknown) => {
  if (error instanceof APIError) {
    console.error('API Error:', {
      code: error.code,
      message: error.message,
      params: error.params
    });
  } else if (error instanceof UploadError) {
    console.error('Upload Error:', {
      code: error.code,
      message: error.message
    });
  } else if (error instanceof UpdatesError) {
    console.error('Updates Error:', {
      code: error.code,
      message: error.message
    });
  } else if (error instanceof VKError) {
    console.error('VK Error:', {
      code: error.code,
      message: error.message,
      cause: error.cause
    });
  } else {
    console.error('Unknown error:', error);
  }
};

vk.updates.on('error', handleError);

try {
  await vk.api.messages.send({ ... });
} catch (error) {
  handleError(error);
}

Type Guards

import { APIError, UploadError, VKError } from 'vk-io';

const isAPIError = (error: unknown): error is APIError => {
  return error instanceof APIError;
};

const isUploadError = (error: unknown): error is UploadError => {
  return error instanceof UploadError;
};

const isVKError = (error: unknown): error is VKError => {
  return error instanceof VKError;
};

try {
  await someOperation();
} catch (error) {
  if (isAPIError(error)) {
    // TypeScript knows error is APIError
    console.log(error.params);
  } else if (isVKError(error)) {
    // TypeScript knows error is VKError
    console.log(error.code);
  }
}

Error Code Enums

VK-IO exports error code enums for type-safe error handling:
import {
  APIErrorCode,
  CollectErrorCode,
  ResourceErrorCode,
  SharedErrorCode,
  UpdatesErrorCode,
  UploadErrorCode
} from 'vk-io';

View Full API Error Codes

See VK’s official documentation for the complete list of API error codes and their meanings.

Build docs developers (and LLMs) love