tonic/transport/
error.rs

1use std::{error::Error as StdError, fmt};
2
3type Source = Box<dyn StdError + Send + Sync + 'static>;
4
5/// Error's that originate from the client or server;
6pub struct Error {
7    inner: ErrorImpl,
8}
9
10struct ErrorImpl {
11    kind: Kind,
12    source: Option<Source>,
13}
14
15#[derive(Debug)]
16pub(crate) enum Kind {
17    Transport,
18    #[cfg(feature = "channel")]
19    InvalidUri,
20    #[cfg(feature = "channel")]
21    InvalidUserAgent,
22    #[cfg(all(feature = "_tls-any", feature = "channel"))]
23    InvalidTlsConfigForUds,
24}
25
26impl Error {
27    pub(crate) fn new(kind: Kind) -> Self {
28        Self {
29            inner: ErrorImpl { kind, source: None },
30        }
31    }
32
33    pub(crate) fn with(mut self, source: impl Into<Source>) -> Self {
34        self.inner.source = Some(source.into());
35        self
36    }
37
38    pub(crate) fn from_source(source: impl Into<crate::BoxError>) -> Self {
39        Error::new(Kind::Transport).with(source)
40    }
41
42    #[cfg(feature = "channel")]
43    pub(crate) fn new_invalid_uri() -> Self {
44        Error::new(Kind::InvalidUri)
45    }
46
47    #[cfg(feature = "channel")]
48    pub(crate) fn new_invalid_user_agent() -> Self {
49        Error::new(Kind::InvalidUserAgent)
50    }
51
52    fn description(&self) -> &str {
53        match &self.inner.kind {
54            Kind::Transport => "transport error",
55            #[cfg(feature = "channel")]
56            Kind::InvalidUri => "invalid URI",
57            #[cfg(feature = "channel")]
58            Kind::InvalidUserAgent => "user agent is not a valid header value",
59            #[cfg(all(feature = "_tls-any", feature = "channel"))]
60            Kind::InvalidTlsConfigForUds => "cannot apply TLS config for unix domain socket",
61        }
62    }
63}
64
65impl fmt::Debug for Error {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        let mut f = f.debug_tuple("tonic::transport::Error");
68
69        f.field(&self.inner.kind);
70
71        if let Some(source) = &self.inner.source {
72            f.field(source);
73        }
74
75        f.finish()
76    }
77}
78
79impl fmt::Display for Error {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str(self.description())
82    }
83}
84
85impl StdError for Error {
86    fn source(&self) -> Option<&(dyn StdError + 'static)> {
87        self.inner
88            .source
89            .as_ref()
90            .map(|source| &**source as &(dyn StdError + 'static))
91    }
92}