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
use std::collections::HashMap;
use std::io;

use crate::ErrorResponse;
use serde::Serialize;

#[derive(Clone, Debug, Serialize)]
pub struct Error {
    code: i32,
    message: String,
    context: HashMap<String, String>,
}

impl Error {
    pub fn from_string(s: impl ToString) -> Self {
        Error {
            code: 1,
            message: s.to_string(),
            context: Default::default(),
        }
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Error {
            code: e.raw_os_error().unwrap_or(1),
            message: e.to_string(),
            context: Default::default(),
        }
    }
}

impl From<anyhow::Error> for Error {
    fn from(e: anyhow::Error) -> Self {
        Self::from_string(e)
    }
}

impl From<ErrorResponse> for Error {
    fn from(e: ErrorResponse) -> Self {
        Error {
            code: e.code,
            message: e.message,
            context: e.context,
        }
    }
}

impl Into<ErrorResponse> for Error {
    fn into(self) -> ErrorResponse {
        ErrorResponse {
            code: self.code,
            message: self.message,
            context: self.context,
        }
    }
}

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

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} (code: {})", self.message, self.code)
    }
}