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
use std::error::Error;

use serde::{Deserialize, Serialize};

/// The error type of the [`ProtocolError`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ProtocolErrorType {
    NotFound,
    HttpMethodNotAllowed,
    BadRequest,
    Unauthorized,
    Internal,
}

/// A "one size fits all" error type for the protocol.
/// Contains a boxed error, and the error type.
#[derive(Debug, thiserror::Error)]
#[error("{error}")]
pub struct ProtocolError {
    pub error_type: ProtocolErrorType,
    #[source]
    pub error: Box<dyn Error + Send + Sync + 'static>,
}

impl ProtocolError {
    pub fn new(
        error_type: ProtocolErrorType,
        error: Box<dyn Error + Send + Sync + 'static>,
    ) -> Self {
        Self { error_type, error }
    }
}

impl From<Box<dyn Error + Send + Sync + 'static>> for ProtocolError {
    fn from(error: Box<dyn Error + Send + Sync + 'static>) -> Self {
        match error.downcast::<Self>() {
            Ok(e) => *e,
            Err(e) => ProtocolError::new(ProtocolErrorType::Internal, e),
        }
    }
}

/// A serializable variant of the protocol error.
/// Contains a description of the error and the error type.
#[derive(Clone, Debug, thiserror::Error, Serialize, Deserialize)]
#[error("{description}")]
pub struct SerializableProtocolError {
    pub error_type: ProtocolErrorType,
    pub description: String,
}

impl From<ProtocolError> for SerializableProtocolError {
    fn from(value: ProtocolError) -> Self {
        Self {
            error_type: value.error_type,
            description: value.error.to_string(),
        }
    }
}

impl From<SerializableProtocolError> for ProtocolError {
    fn from(value: SerializableProtocolError) -> Self {
        Self {
            error_type: value.error_type.clone(),
            error: Box::new(value),
        }
    }
}