safe_vk_common/
error.rs

1use super::Shape;
2use serde_json::Error as SerdeJsonError;
3
4#[rustfmt::skip]
5#[derive(thiserror::Error, Debug)]
6pub enum VkError {
7    #[error("Unknown error occurred. Try to repeat the request later.\nAdditional details: {0}")]
8    UnknownError(String),
9
10    #[error("The application is disabled. VK Error: {0}")]
11    ApplicationDisabled(String),
12
13    #[error("An unknown method was passed. Check that the method name is correct: vk.com/dev/methods.\nAdditional details: {0}")]
14    UnknownMethod(String),
15
16    #[error("Invalid signature. VK Error: {0}")]
17    InvalidSignature(String),
18
19    #[error("User authorization failed. Ensure that you are using the correct authorization scheme.\nAdditional details: {0}")]
20    UserAuthorizationFailed(String),
21
22    #[error("Too many requests per second. Increase the request interval or use the execute method. More info: vk.com/dev/api_requests.\nAdditional details: {0}")]
23    TooManyRequests(String),
24
25    #[error("No permission to perform this action. Check that the necessary permissions have been obtained during authorization.\nAdditional details: {0}")]
26    NoPermissionForAction(String),
27
28    #[error("Invalid request. Check the syntax of the request and the list of used parameters.\nAdditional details: {0}")]
29    InvalidRequest(String),
30
31    #[error("Too many similar actions. Reduce the number of similar requests.\nAdditional details: {0}")]
32    TooManySimilarActions(String),
33
34    #[error("Internal server error occurred. Try to repeat the request later.\nAdditional details: {0}")]
35    InternalServerError(String),
36
37    #[error("In test mode, the application must be disabled or the user must be logged in.\nAdditional details: {0}")]
38    TestModeRestrictions(String),
39
40    #[error("Captcha needed. Process this challenge response as described here: (link to captcha handling).\nAdditional details: {0}")]
41    CaptchaRequired(String),
42
43    #[error("Access denied. Make sure you are using the correct identifiers and that the content is available to the current user on the full version of the site.\nAdditional details: {0}")]
44    AccessDenied(String),
45
46    #[error("HTTPS requests required because the user has enabled secure connection settings. Check the user's settings with account.getInfo.\nAdditional details: {0}")]
47    HttpsRequired(String),
48
49    #[error("User validation required. Redirect the user to the validation page.\nAdditional details: {0}")]
50    ValidationRequired(String),
51
52    #[error("The page has been deleted or blocked.\nAdditional details: {0}")]
53    PageBlockedOrDeleted(String),
54
55    #[error("This action is forbidden for non-Standalone applications. If your application is of type Standalone, make sure you are using redirect_uri=https://oauth.vk.com/blank.html during authorization.\nAdditional details: {0}")]
56    ActionForbiddenForNonStandaloneApps(String),
57
58    #[error("This action is only allowed for Standalone and Open API applications.\nAdditional details: {0}")]
59    ActionAllowedOnlyForStandaloneAndOpenAPI(String),
60
61    #[error("The method has been disabled. Check the current methods available here: vk.com/dev/methods.\nAdditional details: {0}")]
62    MethodDisabled(String),
63
64    #[error("User confirmation required.\nAdditional details: {0}")]
65    UserConfirmationRequired(String),
66
67    #[error("Community access token is invalid.\nAdditional details: {0}")]
68    InvalidCommunityAccessToken(String),
69
70    #[error("Application access token is invalid.\nAdditional details: {0}")]
71    InvalidApplicationAccessToken(String),
72
73    #[error("Limit on the number of method calls has been reached. See details here: https://dev.vk.com/en/api/api-requests#Restrictions%20and%20recommendations.\nAdditional details: {0}")]
74    MethodCallLimitReached(String),
75
76    #[error("The profile is private. The requested information is not available with the used access key.\nAdditional details: {0}")]
77    ProfileIsPrivate(String),
78
79    #[error("One of the required parameters was missing or incorrect. Check the required parameters and their format on the method description page.\nAdditional details: {0}")]
80    MissingOrInvalidParameter(String),
81
82    #[error("Invalid API ID of the application. Find your application in the managed list here: http://vk.com/apps?act=settings and specify the correct API ID in the request.\nAdditional details: {0}")]
83    InvalidApiId(String),
84
85    #[error("Invalid user identifier. Ensure you are using the correct identifier. Convert a short name to an ID using utils.resolveScreenName.\nAdditional details: {0}")]
86    InvalidUserId(String),
87
88    #[error("Invalid timestamp. Get the current time using `utils.getServerTime`.\nAdditional details: {0}")]
89    InvalidTimestamp(String),
90
91    #[error("Access to the album is denied. Make sure you are using the correct identifiers and that access to the requested content is available to the current user on the full version of the site.\nAdditional details: {0}")]
92    AlbumAccessDenied(String),
93
94    #[error("Access to audio is denied. Make sure you are using the correct identifiers and that access to the requested content is available to the current user on the full version of the site.\nAdditional details: {0}")]
95    AudioAccessDenied(String),
96
97    #[error("Access to the group is forbidden. Ensure the current user is a member or manager of the community (for closed and private groups and meetings).\nAdditional details: {0}")]
98    GroupAccessDenied(String),
99
100    #[error("The album is full. Remove unnecessary items from the album or use another album.\nAdditional details: {0}")]
101    AlbumFull(String),
102
103    #[error("Action is forbidden. You must enable voice translations in the application settings.\nAdditional details: {0}")]
104    ActionForbidden(String),
105
106    #[error("No rights to perform operations with the advertising cabinet.\nAdditional details: {0}")]
107    NoRightsForAdOperations(String),
108
109    #[error("An error occurred while working with the advertising cabinet.\nAdditional details: {0}")]
110    AdCabinetError(String),
111}
112
113impl VkError {
114    pub fn from_vk_error_json(json: &serde_json::Value) -> Self {
115        let message = json
116            .get("error_msg")
117            .and_then(|m| m.as_str())
118            .unwrap_or("No additional error message provided.")
119            .to_string();
120        if let Some(code) = json.get("error_code").and_then(|code| code.as_i64()) {
121            match code {
122                1 => Self::UnknownError(message),
123                2 => Self::ApplicationDisabled(message),
124                3 => Self::UnknownMethod(message),
125                4 => Self::InvalidSignature(message),
126                5 => Self::UserAuthorizationFailed(message),
127                6 => Self::TooManyRequests(message),
128                7 => Self::NoPermissionForAction(message),
129                8 => Self::InvalidRequest(message),
130                9 => Self::TooManySimilarActions(message),
131                10 => Self::InternalServerError(message),
132                11 => Self::TestModeRestrictions(message),
133                14 => Self::CaptchaRequired(message),
134                15 => Self::AccessDenied(message),
135                16 => Self::HttpsRequired(message),
136                17 => Self::ValidationRequired(message),
137                18 => Self::PageBlockedOrDeleted(message),
138                20 => Self::ActionForbiddenForNonStandaloneApps(message),
139                21 => Self::ActionAllowedOnlyForStandaloneAndOpenAPI(message),
140                23 => Self::MethodDisabled(message),
141                24 => Self::UserConfirmationRequired(message),
142                27 => Self::InvalidCommunityAccessToken(message),
143                28 => Self::InvalidApplicationAccessToken(message),
144                29 => Self::MethodCallLimitReached(message),
145                30 => Self::ProfileIsPrivate(message),
146                100 => Self::MissingOrInvalidParameter(message),
147                101 => Self::InvalidApiId(message),
148                113 => Self::InvalidUserId(message),
149                150 => Self::InvalidTimestamp(message),
150                200 => Self::AlbumAccessDenied(message),
151                201 => Self::AudioAccessDenied(message),
152                203 => Self::GroupAccessDenied(message),
153                300 => Self::AlbumFull(message),
154                500 => Self::ActionForbidden(message),
155                600 => Self::NoRightsForAdOperations(message),
156                603 => Self::AdCabinetError(message),
157                _ => Self::UnknownError(message),
158            }
159        } else {
160            Self::UnknownError(message)
161        }
162    }
163}
164
165#[derive(thiserror::Error, Debug)]
166pub enum Error {
167    #[error("VK API error: {0}")]
168    VkApi(#[from] VkError),
169
170    /// Error to be used when `peer_id` is not found in callback from VK
171    #[error("peer_id not found in VK response")]
172    PeerIdNotFound,
173
174    #[error("Unexpected JSON response: {0}")]
175    UnexpectedResponse(String),
176
177    #[error("Expected status success (1) but got uknown status {status}")]
178    EventAnswerUnkownStatus { status: i8 },
179
180    #[error("Serde JSON error: {0}")]
181    SerdeJson(#[from] SerdeJsonError),
182
183    #[error("Reqwest error: {0}")]
184    Reqwest(#[from] reqwest::Error),
185
186    #[error("Dimension index {dim} exceeds the maximum allowed shape dimensions (5x10) for shape {shape:?}")]
187    DimOutOfRange { shape: Shape, dim: usize },
188
189    /// Indicates that the listener for a specific command was not found.
190    #[error("Listener not found")]
191    ListenerNotFound,
192
193    /// The event history has become outdated or has been partially lost. This can occur if the client fails to
194    /// poll the server in a timely manner, causing a gap in the event sequence. The client should continue polling
195    /// with the new `ts` value provided. This is not a critical error but indicates that some events might have been missed.
196    #[error("LongPoll history is outdated or partially lost. To continue receiving updates, use the new 'ts' key provided: {new_ts}.")]
197    EventsOutdated { new_ts: String },
198
199    /// The session key used for the Long Poll connection has expired. This requires obtaining a new session key by
200    /// calling the `groups.getLongPollServer` method again. Expired keys are common and expected to happen from time
201    /// to time; they simply indicate that the connection to the Long Poll server needs to be refreshed.
202    #[error("The LongPoll session key has expired. Obtain a new key by calling 'groups.getLongPollServer' again.")]
203    KeyExpired,
204
205    /// All session information has been lost, necessitating the initiation of a new Long Poll session. This error
206    /// typically indicates that the server and key information are no longer valid, possibly due to a significant
207    /// lapse in polling or server-side changes. Start a new session by re-fetching the server, key, and 'ts' values.
208    #[error("The LongPoll session's information is lost. Start a new session by re-fetching the server, key, and 'ts' values.")]
209    InformationLost,
210}
211
212pub type Result<T> = std::result::Result<T, Error>;