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
#![allow(deprecated)]

use data_encoding;
use serde::de;

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

error_chain! {
    errors { 
        Custom(msg: String) {
            description("miscellaneous failure")
            display("failed with reason: {}", msg)
        }
        Parse(msg: String, pos: usize) {
            description("parsing failure")
            display("parsing failed with error: '{}' at position: {}", msg, pos)
        }
        Unsupported
    }

    foreign_links {
        Decoding(data_encoding::DecodeError);
        FromUtf8(string::FromUtf8Error);
        Io(io::Error);
        ParseInt(num::ParseIntError);
        Utf8(str::Utf8Error);
    }
}

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

    }

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

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