1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/// An enum representing the errors that can occur.

#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The exhaustive list of Meilisearch errors: <https://github.com/meilisearch/specifications/blob/main/text/0061-error-format-and-definitions.md>
    /// Also check out: <https://github.com/meilisearch/Meilisearch/blob/main/meilisearch-error/src/lib.rs>
    MeiliSearchError {
        /// The human readable error message
        error_message: String,
        /// The error code of the error.  Officially documented at
        /// <https://docs.meilisearch.com/errors>.
        error_code: ErrorCode,
        /// The type of error (invalid request, internal error, or authentication
        /// error)
        error_type: ErrorType,
        /// A link to the Meilisearch documentation for an error.
        error_link: String,
    },

    /// There is no Meilisearch server listening on the [specified host]
    /// (../client/struct.Client.html#method.new).
    UnreachableServer,
    /// The Meilisearch server returned an invalid JSON for a request.
    ParseError(serde_json::Error),
    /// A timeout happened while waiting for an update to complete.
    Timeout,
    /// This Meilisearch SDK generated an invalid request (which was not sent).
    /// It probably comes from an invalid API key resulting in an invalid HTTP header.
    InvalidRequest,

    /// The http client encountered an error.
    #[cfg(not(target_arch = "wasm32"))]
    HttpError(isahc::Error),
    /// The http client encountered an error.
    #[cfg(target_arch = "wasm32")]
    HttpError(String),
}

/// The type of error that was encountered.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ErrorType {
    /// The submitted request was invalid.
    InvalidRequest,
    /// The Meilisearch instance encountered an internal error.
    Internal,
    /// Authentication was either incorrect or missing.
    Auth,
}

/// The error code.
///
/// Officially documented at <https://docs.meilisearch.com/errors>.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ErrorCode {
    IndexCreationFailed,
    IndexAlreadyExists,
    IndexNotFound,
    InvalidIndexUid,
    InvalidState,
    PrimaryKeyInferenceFailed,
    IndexPrimaryKeyAlreadyPresent,
    InvalidRankingRule,
    InvalidStoreFile,
    MaxFieldsLimitExceeded,
    MissingDocumentId,
    InvalidDocumentId,
    InvalidFilter,
    InvalidSort,
    BadParameter,
    BadRequest,
    DatabaseSizeLimitReached,
    DocumentNotFound,
    InternalError,
    InvalidGeoField,
    InvalidApiKey,
    MissingAuthorizationHeader,
    TaskNotFound,
    DumpNotFound,
    NoSpaceLeftOnDevice,
    PayloadTooLarge,
    UnretrievableDocument,
    SearchError,
    UnsupportedMediaType,
    DumpAlreadyProcessing,
    DumpProcessFailed,
    MissingContentType,
    MalformedPayload,
    InvalidContentType,
    MissingPayload,
    MissingParameter,
    InvalidApiKeyDescription,
    InvalidApiKeyActions,
    InvalidApiKeyIndexes,
    InvalidApiKeyExpiresAt,
    ApiKeyNotFound,

    /// That's unexpected. Please open a GitHub issue after ensuring you are
    /// using the supported version of the Meilisearch server.
    Unknown(UnknownErrorCode),
}

#[derive(Clone)]
pub struct UnknownErrorCode(String);

impl std::fmt::Display for UnknownErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, f)
    }
}
impl std::fmt::Debug for UnknownErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&self.0, f)
    }
}

impl ErrorType {
    /// Converts the error type to the string representation returned by
    /// Meilisearch.
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorType::InvalidRequest => "invalid_request",
            ErrorType::Internal => "internal",
            ErrorType::Auth => "auth",
        }
    }
    /// Converts the error type string returned by Meilisearch into an
    /// `ErrorType` enum. If the error type input is not recognized, None is
    /// returned.
    pub fn parse(input: &str) -> Option<Self> {
        match input {
            "invalid_request" => Some(ErrorType::InvalidRequest),
            "internal" => Some(ErrorType::Internal),
            "auth" => Some(ErrorType::Auth),
            _ => None,
        }
    }
}

impl ErrorCode {
    /// Converts the error code to the string representation returned by
    /// Meilisearch.
    pub fn as_str(&self) -> &str {
        match self {
            ErrorCode::IndexCreationFailed => "index_creation_failed",
            ErrorCode::IndexAlreadyExists => "index_already_exists",
            ErrorCode::IndexNotFound => "index_not_found",
            ErrorCode::InvalidIndexUid => "invalid_index_uid",
            ErrorCode::InvalidState => "invalid_state",
            ErrorCode::PrimaryKeyInferenceFailed => "primary_key_inference_failed",
            ErrorCode::IndexPrimaryKeyAlreadyPresent => "index_primary_key_already_exists",
            ErrorCode::InvalidRankingRule => "invalid_ranking_rule",
            ErrorCode::InvalidStoreFile => "invalid_store_file",
            ErrorCode::MaxFieldsLimitExceeded => "max_field_limit_exceeded",
            ErrorCode::MissingDocumentId => "missing_document_id",
            ErrorCode::InvalidDocumentId => "invalid_document_id",
            ErrorCode::InvalidFilter => "invalid_filter",
            ErrorCode::InvalidSort => "invalid_sort",
            ErrorCode::BadParameter => "bad_parameter",
            ErrorCode::BadRequest => "bad_request",
            ErrorCode::DatabaseSizeLimitReached => "database_size_limit_reached",
            ErrorCode::DocumentNotFound => "document_not_found",
            ErrorCode::InternalError => "internal",
            ErrorCode::InvalidGeoField => "invalid_geo_field",
            ErrorCode::InvalidApiKey => "invalid_api_key",
            ErrorCode::MissingAuthorizationHeader => "missing_authorization_header",
            ErrorCode::TaskNotFound => "task_not_found",
            ErrorCode::DumpNotFound => "dump_not_found",
            ErrorCode::NoSpaceLeftOnDevice => "no_space_left_on_device",
            ErrorCode::PayloadTooLarge => "payload_too_large",
            ErrorCode::UnretrievableDocument => "unretrievable_document",
            ErrorCode::SearchError => "search_error",
            ErrorCode::UnsupportedMediaType => "unsupported_media_type",
            ErrorCode::DumpAlreadyProcessing => "dump_already_processing",
            ErrorCode::DumpProcessFailed => "dump_process_failed",
            ErrorCode::MissingContentType => "missing_content_type",
            ErrorCode::MalformedPayload => "malformed_payload",
            ErrorCode::InvalidContentType => "invalid_content_type",
            ErrorCode::MissingPayload => "missing_payload",
            ErrorCode::MissingParameter => "missing_parameter",
            ErrorCode::InvalidApiKeyDescription => "invalid_api_key_description",
            ErrorCode::InvalidApiKeyActions => "invalid_api_key_actions",
            ErrorCode::InvalidApiKeyIndexes => "invalid_api_key_indexes",
            ErrorCode::InvalidApiKeyExpiresAt => "invalid_api_key_expires_at",
            ErrorCode::ApiKeyNotFound => "api_key_not_found",
            // Other than this variant, all the other `&str`s are 'static
            ErrorCode::Unknown(inner) => &inner.0,
        }
    }
    /// Converts the error code string returned by Meilisearch into an `ErrorCode`
    /// enum. If the error type input is not recognized, `ErrorCode::Unknown`
    /// is returned.
    pub fn parse(input: &str) -> Self {
        match input {
            "index_creation_failed" => ErrorCode::IndexCreationFailed,
            "index_already_exists" => ErrorCode::IndexAlreadyExists,
            "index_not_found" => ErrorCode::IndexNotFound,
            "invalid_index_uid" => ErrorCode::InvalidIndexUid,
            "invalid_state" => ErrorCode::InvalidState,
            "primary_key_inference_failed" => ErrorCode::PrimaryKeyInferenceFailed,
            "index_primary_key_already_exists" => ErrorCode::IndexPrimaryKeyAlreadyPresent,
            "invalid_ranking_rule" => ErrorCode::InvalidRankingRule,
            "invalid_store_file" => ErrorCode::InvalidStoreFile,
            "max_field_limit_exceeded" => ErrorCode::MaxFieldsLimitExceeded,
            "missing_document_id" => ErrorCode::MissingDocumentId,
            "invalid_document_id" => ErrorCode::InvalidDocumentId,
            "invalid_filter" => ErrorCode::InvalidFilter,
            "invalid_sort" => ErrorCode::InvalidSort,
            "bad_parameter" => ErrorCode::BadParameter,
            "bad_request" => ErrorCode::BadRequest,
            "database_size_limit_reached" => ErrorCode::DatabaseSizeLimitReached,
            "document_not_found" => ErrorCode::DocumentNotFound,
            "internal" => ErrorCode::InternalError,
            "invalid_geo_field" => ErrorCode::InvalidGeoField,
            "invalid_api_key" => ErrorCode::InvalidApiKey,
            "missing_authorization_header" => ErrorCode::MissingAuthorizationHeader,
            "task_not_found" => ErrorCode::TaskNotFound,
            "dump_not_found" => ErrorCode::DumpNotFound,
            "no_space_left_on_device" => ErrorCode::NoSpaceLeftOnDevice,
            "payload_too_large" => ErrorCode::PayloadTooLarge,
            "unretrievable_document" => ErrorCode::UnretrievableDocument,
            "search_error" => ErrorCode::SearchError,
            "unsupported_media_type" => ErrorCode::UnsupportedMediaType,
            "dump_already_processing" => ErrorCode::DumpAlreadyProcessing,
            "dump_process_failed" => ErrorCode::DumpProcessFailed,
            "missing_content_type" => ErrorCode::MissingContentType,
            "malformed_payload" => ErrorCode::MalformedPayload,
            "invalid_content_type" => ErrorCode::InvalidContentType,
            "missing_payload" => ErrorCode::MissingPayload,
            "invalid_api_key_description" => ErrorCode::InvalidApiKeyDescription,
            "invalid_api_key_actions" => ErrorCode::InvalidApiKeyActions,
            "invalid_api_key_indexes" => ErrorCode::InvalidApiKeyIndexes,
            "invalid_api_key_expires_at" => ErrorCode::InvalidApiKeyExpiresAt,
            "api_key_not_found" => ErrorCode::ApiKeyNotFound,
            inner => ErrorCode::Unknown(UnknownErrorCode(inner.to_string())),
        }
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            ErrorCode::Unknown(inner) => write!(fmt, "unknown ({})", inner),
            _ => write!(fmt, "{}", self.as_str()),
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Error::MeiliSearchError {
                error_message,
                error_code,
                error_type,
                error_link,
            } => write!(
                fmt,
                "Meilisearch {}: {}: {}. {}",
                error_type.as_str(),
                error_code,
                error_message,
                error_link,
            ),
            Error::UnreachableServer => write!(fmt, "The Meilisearch server can't be reached."),
            Error::InvalidRequest => write!(fmt, "Unable to generate a valid HTTP request. It probably comes from an invalid API key."),
            Error::ParseError(e) => write!(fmt, "Error parsing response JSON: {}", e),
            Error::HttpError(e) => write!(fmt, "HTTP request failed: {}", e),
            Error::Timeout => write!(fmt, "A task did not succeed in time."),
        }
    }
}

impl std::error::Error for Error {}

impl From<&serde_json::Value> for Error {
    fn from(json: &serde_json::Value) -> Error {
        let error_message = json
            .get("message")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| json.to_string());

        let error_link = json
            .get("link")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(String::new);

        let error_type = json
            .get("type")
            .and_then(|v| v.as_str())
            .and_then(ErrorType::parse)
            .unwrap_or(ErrorType::Internal);

        // If the response doesn't contain a type field, the error type
        // is assumed to be an internal error.

        let error_code = json
            .get("code")
            .and_then(|v| v.as_str())
            .map(ErrorCode::parse)
            .unwrap_or_else(|| {
                ErrorCode::Unknown(UnknownErrorCode(String::from("missing error code")))
            });

        Error::MeiliSearchError {
            error_message,
            error_code,
            error_type,
            error_link,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl From<isahc::Error> for Error {
    fn from(error: isahc::Error) -> Error {
        if error.kind() == isahc::error::ErrorKind::ConnectionFailed {
            Error::UnreachableServer
        } else {
            Error::HttpError(error)
        }
    }
}