Skip to main content

mcpkit_rs/
error.rs

1use std::{borrow::Cow, fmt::Display};
2
3#[cfg(any(feature = "client", feature = "server"))]
4use crate::ServiceError;
5pub use crate::model::ErrorData;
6#[deprecated(
7    note = "Use `mcpkit_rs::ErrorData` instead, `mcpkit_rs::ErrorData` could become `RmcpError` in the future."
8)]
9pub type Error = ErrorData;
10impl Display for ErrorData {
11    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12        write!(f, "{}: {}", self.code.0, self.message)?;
13        if let Some(data) = &self.data {
14            write!(f, "({})", data)?;
15        }
16        Ok(())
17    }
18}
19
20impl std::error::Error for ErrorData {}
21
22/// This is an unified error type for the errors could be returned by the service.
23#[derive(Debug, thiserror::Error)]
24#[allow(clippy::large_enum_variant)]
25pub enum RmcpError {
26    #[cfg(any(feature = "client", feature = "server"))]
27    #[error("Service error: {0}")]
28    Service(#[from] ServiceError),
29    #[cfg(feature = "client")]
30    #[error("Client initialization error: {0}")]
31    ClientInitialize(#[from] crate::service::ClientInitializeError),
32    #[cfg(feature = "server")]
33    #[error("Server initialization error: {0}")]
34    ServerInitialize(#[from] crate::service::ServerInitializeError),
35    #[error("Runtime error: {0}")]
36    Runtime(#[from] tokio::task::JoinError),
37    #[error("Transport creation error: {error}")]
38    // TODO: Maybe we can introduce something like `TryIntoTransport` to auto wrap transport type,
39    // but it could be an breaking change, so we could do it in the future.
40    TransportCreation {
41        into_transport_type_name: Cow<'static, str>,
42        into_transport_type_id: std::any::TypeId,
43        #[source]
44        error: Box<dyn std::error::Error + Send + Sync>,
45    },
46    // and cancellation shouldn't be an error?
47
48    // TODO: add more error variants as needed
49    #[error("Task error: {0}")]
50    TaskError(String),
51}
52
53impl RmcpError {
54    pub fn transport_creation<T: 'static>(
55        error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
56    ) -> Self {
57        RmcpError::TransportCreation {
58            into_transport_type_id: std::any::TypeId::of::<T>(),
59            into_transport_type_name: std::any::type_name::<T>().into(),
60            error: error.into(),
61        }
62    }
63}