Skip to main content

apache_avro/
error.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Types for dealing with errors.
19
20use crate::{
21    schema::{Name, RecordSchema, Schema, SchemaKind, UnionSchema},
22    types::{Value, ValueKind},
23};
24use std::num::NonZero;
25use std::{error::Error as _, fmt};
26
27/// Errors encountered by Avro.
28///
29/// To inspect the details of the error use [`details`](Self::details) or [`into_details`](Self::into_details)
30/// to get a [`Details`] which contains more precise error information.
31///
32/// See [`Details`] for all possible errors.
33#[derive(thiserror::Error, Debug)]
34#[repr(transparent)]
35#[error(transparent)]
36pub struct Error {
37    details: Box<Details>,
38}
39
40impl Error {
41    pub fn new(details: Details) -> Self {
42        Self {
43            details: Box::new(details),
44        }
45    }
46
47    pub fn details(&self) -> &Details {
48        &self.details
49    }
50
51    pub fn into_details(self) -> Details {
52        *self.details
53    }
54}
55
56impl From<Details> for Error {
57    fn from(details: Details) -> Self {
58        Self::new(details)
59    }
60}
61
62impl serde::ser::Error for Error {
63    fn custom<T: fmt::Display>(msg: T) -> Self {
64        Self::new(<Details as serde::ser::Error>::custom(msg))
65    }
66}
67
68impl serde::de::Error for Error {
69    fn custom<T: fmt::Display>(msg: T) -> Self {
70        Self::new(<Details as serde::de::Error>::custom(msg))
71    }
72}
73
74#[derive(thiserror::Error)]
75pub enum Details {
76    #[error("Bad Snappy CRC32; expected {expected:x} but got {actual:x}")]
77    SnappyCrc32 { expected: u32, actual: u32 },
78
79    #[error("Invalid u8 for bool: {0}")]
80    BoolValue(u8),
81
82    #[error("Not a fixed value, required for decimal with fixed schema: {0:?}")]
83    FixedValue(Value),
84
85    #[error("Not a bytes value, required for decimal with bytes schema: {0:?}")]
86    BytesValue(Value),
87
88    #[error("Not a string value, required for uuid: {0:?}")]
89    GetUuidFromStringValue(Value),
90
91    #[error("Two schemas with the same fullname were given: {0:?}")]
92    NameCollision(String),
93
94    #[error("Not a fixed or bytes type, required for decimal schema, got: {0:?}")]
95    ResolveDecimalSchema(SchemaKind),
96
97    #[error("Decimal bytes cannot be zero length")]
98    DecimalIsZeroLength,
99
100    #[error("Invalid utf-8 string")]
101    ConvertToUtf8(#[source] std::string::FromUtf8Error),
102
103    #[error("Invalid utf-8 string")]
104    ConvertToUtf8Error(#[source] std::str::Utf8Error),
105
106    /// Describes errors happened while validating Avro data.
107    #[error("Value does not match schema")]
108    Validation,
109
110    /// Describes errors happened while validating Avro data.
111    #[error("Value {value:?} does not match schema {schema:?}: Reason: {reason}")]
112    ValidationWithReason {
113        value: Value,
114        schema: Schema,
115        reason: String,
116    },
117
118    #[error(
119        "{} (maximum allowed: {maximum}). Change the limit using `apache_avro::util::max_allocation_bytes`",
120        if let Some(desired) = desired {
121            format!("Unable to allocate {desired} bytes")
122        } else {
123            "Allocation limit reached with unknown amount of bytes remaining".to_string()
124        },
125    )]
126    MemoryAllocation {
127        desired: Option<usize>,
128        maximum: usize,
129    },
130
131    /// Describe a specific error happening with decimal representation
132    #[error(
133        "Number of bytes requested for decimal sign extension {requested} is less than the number of bytes needed to decode {needed}"
134    )]
135    SignExtend { requested: usize, needed: usize },
136
137    #[error("Failed to read boolean bytes: {0}")]
138    ReadBoolean(#[source] std::io::Error),
139
140    #[error("Failed to read bytes: {0}")]
141    ReadBytes(#[source] std::io::Error),
142
143    #[error("Failed to read string: {0}")]
144    ReadString(#[source] std::io::Error),
145
146    #[error("Failed to read double: {0}")]
147    ReadDouble(#[source] std::io::Error),
148
149    #[error("Failed to read float: {0}")]
150    ReadFloat(#[source] std::io::Error),
151
152    #[error("Failed to read duration: {0}")]
153    ReadDuration(#[source] std::io::Error),
154
155    #[error("Failed to read fixed number of bytes '{1}': : {0}")]
156    ReadFixed(#[source] std::io::Error, usize),
157
158    #[error("Failed to convert &str to UUID: {0}")]
159    ConvertStrToUuid(#[source] uuid::Error),
160
161    #[error("Failed to convert Fixed bytes to UUID. It must be exactly 16 bytes, got {0}")]
162    ConvertFixedToUuid(usize),
163
164    #[error("Failed to convert Bytes to UUID. It must be exactly 16 bytes, got {0}")]
165    ConvertBytesToUuid(usize),
166
167    #[error("Failed to convert String to UUID. Expected at most {0} bytes, got {0}")]
168    ConvertStringToUuid(usize, usize),
169
170    #[error("Failed to convert Fixed bytes to UUID: {0}")]
171    ConvertSliceToUuid(#[source] uuid::Error),
172
173    #[error("Map key is not a string; key type is {0:?}")]
174    MapKeyType(ValueKind),
175
176    #[error("Union index {index} out of bounds: {num_variants}")]
177    GetUnionVariant { index: i64, num_variants: usize },
178
179    #[error(
180        "Enum symbol index out of bounds: got {index} but there are only {num_variants} variants"
181    )]
182    EnumSymbolIndex { index: usize, num_variants: usize },
183
184    #[error("Enum symbol not found {0}")]
185    GetEnumSymbol(String),
186
187    #[error("Unable to decode enum index")]
188    GetEnumUnknownIndexValue,
189
190    #[error("Scale {scale} is greater than precision {precision}")]
191    GetScaleAndPrecision {
192        scale: usize,
193        precision: NonZero<usize>,
194    },
195
196    #[error(
197        "Fixed type number of bytes {size} is not large enough to hold decimal values of precision {precision}"
198    )]
199    GetScaleWithFixedSize {
200        size: usize,
201        precision: NonZero<usize>,
202    },
203
204    #[error("Expected Value::Uuid, got: {0:?}")]
205    GetUuid(Value),
206
207    #[error("Expected Value::BigDecimal, got: {0:?}")]
208    GetBigDecimal(Value),
209
210    #[error("Fixed bytes of size 12 expected, got Fixed of size {0}")]
211    GetDurationFixedBytes(usize),
212
213    #[error("Expected Value::Duration or Value::Fixed(12), got: {0:?}")]
214    ResolveDuration(Value),
215
216    #[error("Expected Value::Decimal, Value::Bytes, Value::Fixed or Value::String, got: {0:?}")]
217    ResolveDecimal(Value),
218
219    #[error("Missing field in record: {0:?}")]
220    GetField(String),
221
222    #[error("Unable to convert to u8, got {0:?}")]
223    GetU8(Value),
224
225    #[deprecated(since = "0.23.0", note = "This error variant is not generated anymore")]
226    #[error("Precision {precision} too small to hold decimal values with {num_bytes} bytes")]
227    ComparePrecisionAndSize {
228        precision: NonZero<usize>,
229        num_bytes: usize,
230    },
231
232    #[error("Precision {precision} too small to hold a decimal value with {digits} digits")]
233    ComparePrecisionAndDigits {
234        precision: NonZero<usize>,
235        digits: usize,
236    },
237
238    #[error("Cannot convert length to i32: {1}")]
239    ConvertLengthToI32(#[source] std::num::TryFromIntError, usize),
240
241    #[error("Expected Value::Date or Value::Int, got: {0:?}")]
242    GetDate(Value),
243
244    #[error("Expected Value::TimeMillis or Value::Int, got: {0:?}")]
245    GetTimeMillis(Value),
246
247    #[error("Expected Value::TimeMicros, Value::Long or Value::Int, got: {0:?}")]
248    GetTimeMicros(Value),
249
250    #[error("Expected Value::TimestampMillis, Value::Long or Value::Int, got: {0:?}")]
251    GetTimestampMillis(Value),
252
253    #[error("Expected Value::TimestampMicros, Value::Long or Value::Int, got: {0:?}")]
254    GetTimestampMicros(Value),
255
256    #[error("Expected Value::TimestampNanos, Value::Long or Value::Int, got: {0:?}")]
257    GetTimestampNanos(Value),
258
259    #[error("Expected Value::LocalTimestampMillis, Value::Long or Value::Int, got: {0:?}")]
260    GetLocalTimestampMillis(Value),
261
262    #[error("Expected Value::LocalTimestampMicros, Value::Long or Value::Int, got: {0:?}")]
263    GetLocalTimestampMicros(Value),
264
265    #[error("Expected Value::LocalTimestampNanos, Value::Long or Value::Int, got: {0:?}")]
266    GetLocalTimestampNanos(Value),
267
268    #[error("Expected Value::Null, got: {0:?}")]
269    GetNull(Value),
270
271    #[error("Expected Value::Boolean, got: {0:?}")]
272    GetBoolean(Value),
273
274    #[error("Expected Value::Int, got: {0:?}")]
275    GetInt(Value),
276
277    #[error("Expected Value::Long or Value::Int, got: {0:?}")]
278    GetLong(Value),
279
280    #[error(r#"Expected Value::Double, Value::Float, Value::Int, Value::Long or Value::String ("NaN", "INF", "Infinity", "-INF" or "-Infinity"), got: {0:?}"#)]
281    GetDouble(Value),
282
283    #[error(r#"Expected Value::Float, Value::Double, Value::Int, Value::Long or Value::String ("NaN", "INF", "Infinity", "-INF" or "-Infinity"), got: {0:?}"#)]
284    GetFloat(Value),
285
286    #[error("Expected Value::Bytes, got: {0:?}")]
287    GetBytes(Value),
288
289    #[error("Expected Value::String, Value::Bytes or Value::Fixed, got: {0:?}")]
290    GetString(Value),
291
292    #[error("Expected Value::Enum, got: {0:?}")]
293    GetEnum(Value),
294
295    #[error("Fixed size mismatch, expected: {size}, got: {n}")]
296    CompareFixedSizes { size: usize, n: usize },
297
298    #[error("String expected for fixed, got: {0:?}")]
299    GetStringForFixed(Value),
300
301    #[error("String codepoints must be in the range 0-255 to resolve to Fixed, got: {0:?}")]
302    ResolveFixed(Value),
303
304    #[error("Enum default {symbol:?} is not among allowed symbols {symbols:?}")]
305    GetEnumDefault {
306        symbol: String,
307        symbols: Vec<String>,
308    },
309
310    #[error("Enum value index {index} is out of bounds {nsymbols}")]
311    GetEnumValue { index: usize, nsymbols: usize },
312
313    #[error("Key {0} not found in decimal metadata JSON")]
314    GetDecimalMetadataFromJson(&'static str),
315
316    #[error("Could not find matching type in {schema:?} for {value:?}")]
317    FindUnionVariant { schema: UnionSchema, value: Value },
318
319    #[error("Union type should not be empty")]
320    EmptyUnion,
321
322    #[error("Array({expected:?}) expected, got {other:?}")]
323    GetArray { expected: SchemaKind, other: Value },
324
325    #[error("Map({expected:?}) expected, got {other:?}")]
326    GetMap { expected: SchemaKind, other: Value },
327
328    #[error("Record with fields {expected:?} expected, got {other:?}")]
329    GetRecord {
330        expected: Vec<(String, SchemaKind)>,
331        other: Value,
332    },
333
334    #[error("No `name` field")]
335    GetNameField,
336
337    #[error("Expected a string for the `namespace` field, got a {0}")]
338    GetNamespaceFieldWrongType(&'static str),
339
340    #[error("No `name` in record field")]
341    GetNameFieldFromRecord,
342
343    #[error("Unions may not directly contain a union")]
344    GetNestedUnion,
345
346    #[error(
347        "Found two different maps while building Union: Schema::Map({0:?}), Schema::Map({1:?})"
348    )]
349    GetUnionDuplicateMap(Schema, Schema),
350
351    #[error(
352        "Found two different arrays while building Union: Schema::Array({0:?}), Schema::Array({1:?})"
353    )]
354    GetUnionDuplicateArray(Schema, Schema),
355
356    #[error("Unions cannot contain duplicate types, found at least two {0:?}")]
357    GetUnionDuplicate(SchemaKind),
358
359    #[error("Unions cannot contain more than one named schema with the same name: {0}")]
360    GetUnionDuplicateNamedSchemas(String),
361
362    #[error("One union type {0:?} must match the `default`'s value type {1:?}")]
363    GetDefaultUnion(SchemaKind, ValueKind),
364
365    #[error("`default`'s value type of field `{0}` in `{1}` must be a `{2:#}`. Got: {3:?}")]
366    GetDefaultRecordField(String, String, String, serde_json::Value),
367
368    #[error("JSON number {0} could not be converted into an Avro value as it's too large")]
369    JsonNumberTooLarge(serde_json::Number),
370
371    #[error("JSON value {0} claims to be u64 but cannot be converted")]
372    GetU64FromJson(serde_json::Number),
373
374    #[error("JSON value {0} claims to be i64 but cannot be converted")]
375    GetI64FromJson(serde_json::Number),
376
377    #[error("Cannot convert u64 to usize: {1}")]
378    ConvertU64ToUsize(#[source] std::num::TryFromIntError, u64),
379
380    #[error("Cannot convert i64 to usize: {1}")]
381    ConvertI64ToUsize(#[source] std::num::TryFromIntError, i64),
382
383    #[error("Cannot convert i32 to usize: {1}")]
384    ConvertI32ToUsize(#[source] std::num::TryFromIntError, i32),
385
386    #[error("Cannot convert i64 to u64: {1}")]
387    ConvertI64ToU64(#[source] std::num::TryFromIntError, i64),
388
389    #[error("Cannot convert i32 to u64: {1}")]
390    ConvertI32ToU64(#[source] std::num::TryFromIntError, i32),
391
392    #[error("Cannot convert i64 to u128: {1}")]
393    ConvertI64ToU128(#[source] std::num::TryFromIntError, i64),
394
395    #[error("Cannot convert i32 to u128: {1}")]
396    ConvertI32ToU128(#[source] std::num::TryFromIntError, i32),
397
398    #[error("Cannot convert usize to i64: {1}")]
399    ConvertUsizeToI64(#[source] std::num::TryFromIntError, usize),
400
401    #[error("Invalid JSON value for decimal precision/scale integer: {0}")]
402    GetPrecisionOrScaleFromJson(serde_json::Number),
403
404    #[error("Failed to parse schema from JSON")]
405    ParseSchemaJson(#[source] serde_json::Error),
406
407    #[error("Failed to read schema")]
408    ReadSchemaFromReader(#[source] std::io::Error),
409
410    #[error("Must be a JSON string, object or array")]
411    ParseSchemaFromValidJson,
412
413    #[error("Unknown primitive type: {0}")]
414    ParsePrimitive(String),
415
416    #[error("Unknown primitive type: '{0}'. Did you mean '{1}' ?")]
417    ParsePrimitiveSimilar(String, &'static str),
418
419    #[error("invalid JSON for {key:?}: {value:?}")]
420    GetDecimalMetadataValueFromJson {
421        key: String,
422        value: serde_json::Value,
423    },
424
425    #[error("The decimal precision ({precision}) must be bigger or equal to the scale ({scale})")]
426    DecimalPrecisionLessThanScale {
427        precision: NonZero<usize>,
428        scale: usize,
429    },
430
431    #[error("The decimal precision ({precision}) must be a non-zero positive number")]
432    DecimalPrecisionMuBePositive { precision: usize },
433
434    #[error("Unreadable length for big decimal inner bytes: {0}")]
435    BigDecimalLen(#[source] Box<Error>),
436
437    #[error("Unreadable big decimal scale")]
438    BigDecimalScale,
439
440    #[error("No `type` field found for `logicalType`")]
441    GetLogicalTypeField,
442
443    #[error("logicalType must be a string, but is {0:?}")]
444    GetLogicalTypeFieldType(serde_json::Value),
445
446    #[error("Unknown complex type: {0}")]
447    GetComplexType(serde_json::Value),
448
449    #[error("No `type` in complex type")]
450    GetComplexTypeField,
451
452    #[error("No `type` in record field")]
453    GetRecordFieldTypeField,
454
455    #[error("No `fields` in record")]
456    GetRecordFieldsJson,
457
458    #[error("Expected an object in the array of the `fields` field, got a {0}")]
459    GetRecordFieldsArrayInvalidType(&'static str),
460
461    #[error("Expected an array of objects for the `fields` field, got a {0}")]
462    GetRecordFieldsInvalidType(&'static str),
463
464    #[error("No `symbols` field in enum")]
465    GetEnumSymbolsField,
466
467    #[error("Expected an array of strings for the `symbols` field, got a {0}")]
468    GetEnumSymbolsFieldInvalidType(&'static str),
469
470    #[error("Expected a string in the array of the `symbols` field, got a {0}")]
471    GetEnumSymbolsFieldArrayInvalidType(&'static str),
472
473    #[error("Unable to parse `symbols` in enum")]
474    GetEnumSymbols,
475
476    #[error("Invalid enum symbol name {0}")]
477    EnumSymbolName(String),
478
479    #[error("Invalid field name {0}")]
480    FieldName(String),
481
482    #[error("Duplicate field name {0}")]
483    FieldNameDuplicate(String),
484
485    #[error("Invalid schema name {0}. It must match the regex '{1}'")]
486    InvalidSchemaName(String, &'static str),
487
488    #[error("Invalid namespace {0}. It must match the regex '{1}'")]
489    InvalidNamespace(String, &'static str),
490
491    #[error(
492        "Invalid schema: There is no type called '{0}', if you meant to define a non-primitive schema, it should be defined inside `type` attribute."
493    )]
494    InvalidSchemaRecord(String),
495
496    #[error("Duplicate enum symbol {0}")]
497    EnumSymbolDuplicate(String),
498
499    #[error("Default value for an enum must be a string! Got: {0}")]
500    EnumDefaultWrongType(serde_json::Value),
501
502    #[error("Default value for an array must be an array! Got: {0}")]
503    ArrayDefaultWrongType(serde_json::Value),
504
505    #[error("Default value for an array must be an array of {0}! Found: {1:?}")]
506    ArrayDefaultWrongInnerType(Schema, Value),
507
508    #[error("Default value for a map must be an object! Got: {0}")]
509    MapDefaultWrongType(serde_json::Value),
510
511    #[error("Default value for a map must be an object with (String, {0})! Found: (String, {1:?})")]
512    MapDefaultWrongInnerType(Schema, Value),
513
514    #[error("No `items` in array")]
515    GetArrayItemsField,
516
517    #[error("No `values` in map")]
518    GetMapValuesField,
519
520    #[error("Fixed schema `size` value must be a positive integer: {0}")]
521    GetFixedSizeFieldPositive(serde_json::Value),
522
523    #[error("Fixed schema has no `size`")]
524    GetFixedSizeField,
525
526    #[error("Expected an unsigned integer for the `size` field, got a {0}")]
527    GetFixedSizeFieldInvalidType(&'static str),
528
529    #[error("Expected an array of strings for the `aliases` field, got a {0}")]
530    GetAliasesFieldInvalidType(&'static str),
531
532    #[error("Expected a string in the array for the `aliases` field, got a {0}")]
533    GetAliasesFieldArrayInvalidType(&'static str),
534
535    #[error("Expected a string for the `{0}` field, got a {1}")]
536    GetStringInvalidType(&'static str, &'static str),
537
538    #[error("Failed to decompress with flate: {0}")]
539    DeflateDecompress(#[source] std::io::Error),
540
541    #[cfg(feature = "snappy")]
542    #[error("Failed to compress with snappy: {0}")]
543    SnappyCompress(#[source] snap::Error),
544
545    #[cfg(feature = "snappy")]
546    #[error("Failed to get snappy decompression length: {0}")]
547    GetSnappyDecompressLen(#[source] snap::Error),
548
549    #[cfg(feature = "snappy")]
550    #[error("Snappy-compressed block is {0} bytes, too short to contain the trailing CRC32")]
551    BadSnappyLength(usize),
552
553    #[cfg(feature = "snappy")]
554    #[error("Failed to decompress with snappy: {0}")]
555    SnappyDecompress(#[source] snap::Error),
556
557    #[error("Failed to compress with zstd: {0}")]
558    ZstdCompress(#[source] std::io::Error),
559
560    #[error("Failed to decompress with zstd: {0}")]
561    ZstdDecompress(#[source] std::io::Error),
562
563    #[cfg(feature = "bzip")]
564    #[error("Failed to decompress with bzip2: {0}")]
565    Bzip2Decompress(#[source] std::io::Error),
566
567    #[cfg(feature = "xz")]
568    #[error("Failed to decompress with xz: {0}")]
569    XzDecompress(#[source] std::io::Error),
570
571    #[error("Failed to read header: {0}")]
572    ReadHeader(#[source] std::io::Error),
573
574    #[error("wrong magic in header")]
575    HeaderMagic,
576
577    #[error("Message Header mismatch. Expected: {0:?}. Actual: {1:?}")]
578    SingleObjectHeaderMismatch(Vec<u8>, Vec<u8>),
579
580    #[error("Failed to get JSON from avro.schema key in map")]
581    GetAvroSchemaFromMap,
582
583    #[error("no metadata in header")]
584    GetHeaderMetadata,
585
586    #[error("Failed to read marker bytes: {0}")]
587    ReadMarker(#[source] std::io::Error),
588
589    #[error("Failed to read block marker bytes: {0}")]
590    ReadBlockMarker(#[source] std::io::Error),
591
592    #[error("Read into buffer failed: {0}")]
593    ReadIntoBuf(#[source] std::io::Error),
594
595    #[error(
596        "Invalid sync marker! The sync marker in the data block \
597        doesn't match the file header's sync marker. This likely \
598        indicates data corruption, truncated file, or incorrectly \
599        concatenated Avro files. Verify file integrity and ensure \
600        proper file transmission or creation."
601    )]
602    GetBlockMarker,
603
604    #[error("Overflow when decoding integer value")]
605    IntegerOverflow,
606
607    #[error(
608        "Maximum decode recursion depth reached (maximum: {maximum}). Change the limit using `apache_avro::util::max_decode_recursion_depth`"
609    )]
610    DecodeRecursionLimit { maximum: usize },
611
612    #[error("Failed to read bytes for decoding variable length integer: {0}")]
613    ReadVariableIntegerBytes(#[source] std::io::Error),
614
615    #[error("Decoded integer out of range for i32: {1}: {0}")]
616    ZagI32(#[source] std::num::TryFromIntError, i64),
617
618    #[error("Did not read any bytes, block is corrupt")]
619    ReadBlock,
620
621    #[error("Failed to serialize value into Avro value: {0}")]
622    SerializeValue(String),
623
624    #[error("Failed to serialize value of type `{value_type}` using Schema::{schema:?}: {value}")]
625    SerializeValueWithSchema {
626        value_type: &'static str,
627        value: String,
628        schema: Schema,
629    },
630
631    #[error("{position} is not a valid index for fields in {schema:?}")]
632    SerializeRecordUnknownFieldIndex {
633        position: usize,
634        schema: RecordSchema,
635    },
636
637    #[error("Failed to serialize field '{field_name}' of record {record_schema:?}: {error}")]
638    SerializeRecordFieldWithSchema {
639        field_name: String,
640        record_schema: RecordSchema,
641        error: String,
642    },
643
644    #[error("Missing default for skipped field '{field_name}' of schema {schema:?}")]
645    MissingDefaultForSkippedField {
646        field_name: String,
647        schema: RecordSchema,
648    },
649
650    #[error("Failed to deserialize Avro value into value: {0}")]
651    DeserializeValue(String),
652
653    #[error("Failed to deserialize value of type {value_type} using schema {schema:?}: {value}")]
654    DeserializeSchemaAware {
655        value_type: &'static str,
656        value: String,
657        schema: Schema,
658    },
659
660    #[error("Only expected `deserialize_identifier` to be called but `{0}` was called")]
661    DeserializeIdentifier(&'static str),
662
663    #[error("Failed to write buffer bytes during flush: {0}")]
664    WriteBytes(#[source] std::io::Error),
665
666    #[error("Failed to flush inner writer during flush: {0}")]
667    FlushWriter(#[source] std::io::Error),
668
669    #[error("Failed to write marker: {0}")]
670    WriteMarker(#[source] std::io::Error),
671
672    #[error("Failed to convert JSON to string: {0}")]
673    ConvertJsonToString(#[source] serde_json::Error),
674
675    /// Error while converting float to JSON value
676    #[error("failed to convert avro float to json: {0}")]
677    ConvertF64ToJson(f64),
678
679    /// Error while resolving [`Schema::Ref`]
680    #[error("Unresolved schema reference: {0}")]
681    SchemaResolutionError(Name),
682
683    #[error("The file metadata is already flushed.")]
684    FileHeaderAlreadyWritten,
685
686    #[error("Metadata keys starting with 'avro.' are reserved for internal usage: {0}.")]
687    InvalidMetadataKey(String),
688
689    /// Error when two named schema have the same fully qualified name
690    #[error("Two named schema defined for same fullname: {0}.")]
691    AmbiguousSchemaDefinition(Name),
692
693    #[error("Signed decimal bytes length {0} not equal to fixed schema size {1}.")]
694    EncodeDecimalAsFixedError(usize, usize),
695
696    #[error("There is no entry for '{0}' in the lookup table: {1}.")]
697    NoEntryInLookupTable(String, String),
698
699    #[error("Can only encode value type {value_kind:?} as one of {supported_schema:?}")]
700    EncodeValueAsSchemaError {
701        value_kind: ValueKind,
702        supported_schema: Vec<SchemaKind>,
703    },
704    #[error("Internal buffer not drained properly. Re-initialize the single object writer struct!")]
705    IllegalSingleObjectWriterState,
706
707    #[error("Codec '{0}' is not supported/enabled")]
708    CodecNotSupported(String),
709
710    #[error("Invalid Avro data! Cannot read codec type from value that is not Value::Bytes.")]
711    BadCodecMetadata,
712
713    #[error("Cannot convert a slice to Uuid: {0}")]
714    UuidFromSlice(#[source] uuid::Error),
715
716    #[error("Expected String for Map key when serializing a flattened struct")]
717    MapFieldExpectedString,
718
719    #[error("No key for value when serializing a map")]
720    MapNoKey,
721
722    #[error(
723        "The implementation of `SchemaNameValidator` is incorrect! It returned an out-of-bounds index or provided a regex that did not capture a group named `name`"
724    )]
725    InvalidSchemaNameValidatorImplementation,
726
727    #[error(
728        "Not all tuple fields were serialized, expected to serialize element at position {position} of a {total_elements}-tuple but `SerializeTuple::end()` was called"
729    )]
730    SerializeTupleMissingElements {
731        position: usize,
732        total_elements: usize,
733    },
734
735    #[error("The value is invalid for the given schema: {0}")]
736    InvalidValueForSchema(String),
737
738    #[error("The value is invalid for all the given schemas: {0:?}")]
739    InvalidValueForAllSchemas(Vec<String>),
740}
741
742#[derive(thiserror::Error, PartialEq)]
743pub enum CompatibilityError {
744    #[error(
745        "Incompatible schema types! Writer schema is '{writer_schema_type}', but reader schema is '{reader_schema_type}'"
746    )]
747    WrongType {
748        writer_schema_type: String,
749        reader_schema_type: String,
750    },
751
752    #[error("Incompatible schema types! The {schema_type} should have been {expected_type:?}")]
753    TypeExpected {
754        schema_type: String,
755        expected_type: Vec<SchemaKind>,
756    },
757
758    #[error(
759        "Incompatible schemata! Field '{0}' in reader schema does not match the type in the writer schema"
760    )]
761    FieldTypeMismatch(String, #[source] Box<CompatibilityError>),
762
763    #[error("Incompatible schemata! Field '{0}' in reader schema must have a default value")]
764    MissingDefaultValue(String),
765
766    #[error("Incompatible schemata! Reader's symbols contain none of the writer's symbols")]
767    MissingSymbols,
768
769    #[error("Incompatible schemata! All elements in union must match for both schemas")]
770    MissingUnionElements,
771
772    #[error("Incompatible schemata! At least one element in the union must match the schema")]
773    SchemaMismatchAllUnionElements,
774
775    #[error("Incompatible schemata! Size doesn't match for fixed")]
776    FixedMismatch,
777
778    #[error(
779        "Incompatible schemata! Decimal precision and/or scale don't match, reader: ({r_precision},{r_scale}), writer: ({w_precision},{w_scale})"
780    )]
781    DecimalMismatch {
782        r_precision: NonZero<usize>,
783        r_scale: usize,
784        w_precision: NonZero<usize>,
785        w_scale: usize,
786    },
787
788    #[error(
789        "Incompatible schemata! The name must be the same for both schemas. Writer's name {writer_name} and reader's name {reader_name}"
790    )]
791    NameMismatch {
792        writer_name: String,
793        reader_name: String,
794    },
795
796    #[error(
797        "Incompatible schemata! Unknown type for '{0}'. Make sure that the type is a valid one"
798    )]
799    Inconclusive(String),
800}
801
802impl serde::ser::Error for Details {
803    fn custom<T: fmt::Display>(msg: T) -> Self {
804        Details::SerializeValue(msg.to_string())
805    }
806}
807
808impl serde::de::Error for Details {
809    fn custom<T: fmt::Display>(msg: T) -> Self {
810        Details::DeserializeValue(msg.to_string())
811    }
812}
813
814impl fmt::Debug for Details {
815    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
816        let mut msg = self.to_string();
817        if let Some(e) = self.source() {
818            msg.extend([": ", &e.to_string()]);
819        }
820        write!(f, "{msg}")
821    }
822}
823
824impl fmt::Debug for CompatibilityError {
825    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826        let mut msg = self.to_string();
827        if let Some(e) = self.source() {
828            msg.extend([": ", &e.to_string()]);
829        }
830        write!(f, "{msg}")
831    }
832}