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

use std::fmt;

pub use error_chain::bail;
use error_chain::error_chain;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{self, Visitor};

error_chain! {
    types {
        Error,
        ErrorKind,
        ResultExt,
        Result;
    }

    foreign_links {
        Url(url::ParseError);
        Io(std::io::Error);
        Serde(serde_json::error::Error);
        Recv(std::sync::mpsc::RecvError);
    }
}

/// In order to send Jobs, containing Results and hence Errors, back and fore between the Client
/// and the Server it must implement Serialize and Deserialize - but we can't derive it as
/// the structs are declared from the error_chain!() macro. So we have to implement them.
impl Serialize for crate::errors::Error {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

struct ErrorVisitor;

impl<'de> Visitor<'de> for ErrorVisitor {
    type Value = crate::errors::Error;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("an Error string")
    }

    fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
        where
            E: de::Error,
    {
        Ok(crate::errors::Error::from(value))
    }
}

impl<'de> Deserialize<'de> for crate::errors::Error {
    fn deserialize<D>(deserializer: D) -> std::result::Result<crate::errors::Error, D::Error>
        where
            D: Deserializer<'de>,
    {
        deserializer.deserialize_str(ErrorVisitor)
    }
}

/// We want to clone Job, which contains Result which contains Error, but can't just derive it as
/// it is generated by the error_chain!() macro, so we implement it manually
impl Clone for crate::errors::Error {
    fn clone(&self) -> Self {
        crate::errors::Error::from(self.to_string())
    }
}