Advanced usage

Errors handling

The easiest way to catch an error is using the try-except statement:

import vk
from vk.exceptions import VkAPIError

api = vk.API(access_token='Invalid access token')

try:
    user = api.users.get(user_ids=1)
except VkAPIError as e:
    print(e)

# 5. User authorization failed: invalid access_token (4).. request_params = { ... }

Class vk.exceptions.VkAPIError provides basic functionality for error processing

exception vk.exceptions.VkAPIError(error_data)[source]

Class to represent a VK API error

Parameters

error_data (dict) – Parsed JSON object of error

method

The method whose call resulted in an error. Relevant only for errors that occurred during the execute method

Type

Union[str, None]

code

Error code. To conveniently determine the type of error, you can use vk.exceptions.ErrorCodes enumeration class

Type

int

message

A message explaining the nature and/or cause of the error

Type

str

request_params

Dictionary (param-value) of request parameters that were passed to the API method

Type

dict

redirect_uri

The link you need to click to pass validation. None for all errors except 17

Type

Union[str, None]

captcha_sid

Captcha SID. None for all errors except 14

Type

Union[str, None]

captcha_img

Link to the image to be solved. None for all errors except 14

Type

Union[str, None]

For a simpler definition of the type of error, you can use the vk.exceptions.ErrorCodes

class vk.exceptions.ErrorCodes(value)[source]

Enumeration object of VK API error codes. See official documentation for more details

AUTHORIZATION_FAILED = 5

Invalid access token

PERMISSION_IS_DENIED = 7

No rights to perform this action

CAPTCHA_NEEDED = 14

Need to enter the code from the image (Captcha)

ACCESS_DENIED = 15

No access to call this method

INVALID_USER_ID = 113

Invalid user ID or user deactivated

import vk
from vk.exceptions import ErrorCodes, VkAPIError

api = vk.API(access_token='Invalid access token', v='5.131')

try:
    user = api.users.get(user_ids=1)
except VkAPIError as e:
    print(e.code == ErrorCodes.AUTHORIZATION_FAILED)

# True

Global errors handling

Some errors can occur in any request and handling them every time the method called will be a very difficult task, so you can define a global handler for each error

APIBase.on_api_error(request)[source]

Default API error handler that handles all errros and raises them. You can add a handler for a specific error by redefining it in your class and appending the error code to the method name. In this case, the redefined method will be called instead of on_api_error(). The vk.exceptions.VkAPIError object can be obtained via request.api_error

Parameters

request (vk.api.APIRequest) – API request object

Example

import vk

class API(vk.APIBase):
    def on_api_error_1(self, request):
        print('An unknown error has occurred :(')

api = API()

For some popular errors, the vk.session.API already has its own handlers, for example, for processing captcha:

API.on_api_error_14(request)[source]

Captcha error handler. Retrieves captcha via API.get_captcha_key() and resends request

API.get_captcha_key(api_error)[source]

Callback to retrieve CAPTCHA key. Default behavior is to raise exception, redefine in a subclass

Parameters

api_error (vk.exceptions.VkAPIError) – Captcha error that occurred

Returns

Captcha solution (a short string consisting of lowercase letters and numbers)

Connection parameters

You can specify additional connection parameters in each API implementation: timeout, which specifies the time to complete the request (default is 10) and proxy, which specifies which proxy to use (default is None).

import vk

api = vk.API(
    ...
    timeout=5,
    proxy='socks5://127.0.0.1:9050'
)

Interactive

class vk.session.InteractiveMixin[source]

Mixin that receives the necessary data from the console

Example

import vk
from vk.session import InteractiveMixin

class API(InteractiveMixin, vk.API):
    pass

api = API()

# The input will appear: `VK API access token: `