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
use serde::de;

use std::fmt::Display;
use std::io;
use std::num;
use std::str;
use std::string;

/// Error type for `serde_qs`.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Custom string-based error
    #[error("failed with reason: {0}")]
    Custom(String),

    /// Parse error at a specified position in the query string
    #[error("parsing failed with error: '{0}' at position: {1}")]
    Parse(String, usize),

    /// Unsupported type that `serde_qs` can't serialize into a query string
    #[error("unsupported type for serialization")]
    Unsupported,

    /// Error decoding `BASE64URL` data
    #[error(transparent)]
    Decoding(#[from] data_encoding::DecodeError),

    /// Error proessing UTF-8 for a `String`
    #[error(transparent)]
    FromUtf8(#[from] string::FromUtf8Error),

    /// I/O error
    #[error(transparent)]
    Io(#[from] io::Error),

    /// Error parsing a number
    #[error(transparent)]
    ParseInt(#[from] num::ParseIntError),

    /// Error processing UTF-8 for a `str`
    #[error(transparent)]
    Utf8(#[from] str::Utf8Error),
}

impl Error {
    /// Generate error to show top-level type cannot be deserialized.
    pub fn top_level(object: &'static str) -> Self {
        Self::Custom(format!(
            "cannot deserialize {} at the top level.\
             Try deserializing into a struct.",
            object
        ))
    }

    /// Generate a parsing error message with position.
    pub fn parse_err<T>(msg: T, position: usize) -> Self
    where
        T: Display,
    {
        Self::Parse(msg.to_string(), position)
    }
}

impl de::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        Self::Custom(msg.to_string())
    }
}

pub type Result<T, E = Error> = core::result::Result<T, E>;