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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Actor errors.

use super::actor::AnyValue;
use super::language;
use super::schemas::protocol as P;

use preserves::value::NestedValue;
use preserves::value::Value;
use preserves_schema::Codec;
use preserves_schema::ParseError;

pub type Error = P::Error<AnyValue>;

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

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

/// Construct an [`Error`] with the given `message` and `detail`.
///
/// When no relevant detail exists, convention is to set `detail` to `false`.
pub fn error<Detail>(message: &str, detail: Detail) -> Error where AnyValue: From<Detail> {
    Error {
        message: message.to_owned(),
        detail: AnyValue::from(detail),
    }
}

/// Encodes an [`ActorResult`][crate::actor::ActorResult] as an
/// [`AnyValue`][crate::actor::AnyValue].
///
/// Used primarily when attempting to perform an
/// [`Activation`][crate::actor::Activation] on an already-terminated
/// actor.
pub fn encode_error(result: Result<(), Error>) -> AnyValue {
    match result {
        Ok(()) => {
            let mut r = Value::record(AnyValue::symbol("Ok"), 1);
            r.fields_vec_mut().push(Value::record(AnyValue::symbol("tuple"), 0).finish().wrap());
            r.finish().wrap()
        }
        Err(e) => {
            let mut r = Value::record(AnyValue::symbol("Err"), 1);
            r.fields_vec_mut().push(language().unparse(&e));
            r.finish().wrap()
        }
    }
}

impl<'a> From<&'a str> for Error {
    fn from(v: &'a str) -> Self {
        error(v, AnyValue::new(false))
    }
}

impl From<std::io::Error> for Error {
    fn from(v: std::io::Error) -> Self {
        error(&format!("{}", v), AnyValue::new(false))
    }
}

impl From<ParseError> for Error {
    fn from(v: ParseError) -> Self {
        error(&format!("{}", v), AnyValue::new(false))
    }
}

impl From<preserves::error::Error> for Error {
    fn from(v: preserves::error::Error) -> Self {
        error(&format!("{}", v), AnyValue::new(false))
    }
}

impl From<Box<dyn std::error::Error>> for Error {
    fn from(v: Box<dyn std::error::Error>) -> Self {
        match v.downcast::<Error>() {
            Ok(e) => *e,
            Err(v) => error(&format!("{}", v), AnyValue::new(false)),
        }
    }
}

impl From<Box<dyn std::error::Error + Send + Sync + 'static>> for Error {
    fn from(v: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self {
        match v.downcast::<Error>() {
            Ok(e) => *e,
            Err(v) => error(&format!("{}", v), AnyValue::new(false)),
        }
    }
}