multilink/
error.rs

1use std::error::Error;
2
3use serde::{Deserialize, Serialize};
4
5/// The error type of the [`ProtocolError`].
6#[derive(Clone, Debug, Serialize, Deserialize)]
7pub enum ProtocolErrorType {
8    NotFound,
9    HttpMethodNotAllowed,
10    BadRequest,
11    Unauthorized,
12    Internal,
13}
14
15/// A "one size fits all" error type for the protocol.
16/// Contains a boxed error, and the error type.
17#[derive(Debug, thiserror::Error)]
18#[error("{error}")]
19pub struct ProtocolError {
20    pub error_type: ProtocolErrorType,
21    #[source]
22    pub error: Box<dyn Error + Send + Sync + 'static>,
23}
24
25impl ProtocolError {
26    pub fn new(
27        error_type: ProtocolErrorType,
28        error: Box<dyn Error + Send + Sync + 'static>,
29    ) -> Self {
30        Self { error_type, error }
31    }
32}
33
34impl From<Box<dyn Error + Send + Sync + 'static>> for ProtocolError {
35    fn from(error: Box<dyn Error + Send + Sync + 'static>) -> Self {
36        match error.downcast::<Self>() {
37            Ok(e) => *e,
38            Err(e) => ProtocolError::new(ProtocolErrorType::Internal, e),
39        }
40    }
41}
42
43/// A serializable variant of the protocol error.
44/// Contains a description of the error and the error type.
45#[derive(Clone, Debug, thiserror::Error, Serialize, Deserialize)]
46#[error("{description}")]
47pub struct SerializableProtocolError {
48    pub error_type: ProtocolErrorType,
49    pub description: String,
50}
51
52impl From<ProtocolError> for SerializableProtocolError {
53    fn from(value: ProtocolError) -> Self {
54        Self {
55            error_type: value.error_type,
56            description: value.error.to_string(),
57        }
58    }
59}
60
61impl From<SerializableProtocolError> for ProtocolError {
62    fn from(value: SerializableProtocolError) -> Self {
63        Self {
64            error_type: value.error_type.clone(),
65            error: Box::new(value),
66        }
67    }
68}