rpc_io/error.rs
1//! [`Error`] (the connection) and [`CallError`] (one outgoing request).
2
3use std::{fmt, io};
4
5use jsonx_lib::Kind;
6
7use crate::{error_object::ErrorObject, framing::FrameError};
8
9/// Why the connection, or an operation on it, failed.
10///
11/// # Examples
12///
13/// ```
14/// use rpc_io::{Error, FrameError, Framing, Router};
15///
16/// // A broken header section ends the session: the stream has no reliable
17/// // message boundary left.
18/// let input: &[u8] = b"Content-Length: x\r\n\r\n";
19/// let result = rpc_io::serve(input, std::io::sink(), Framing::ContentLength, Router::new());
20/// assert!(matches!(result, Err(Error::Frame(FrameError::InvalidContentLength))));
21/// ```
22#[derive(Debug)]
23#[non_exhaustive]
24pub enum Error {
25 /// Reading or writing the transport failed. The connection is closed.
26 Io(io::Error),
27 /// The input stream broke its framing in a way that leaves no reliable
28 /// message boundary (see [`FrameError::is_recoverable`]). The connection is
29 /// closed.
30 Frame(FrameError),
31 /// The connection is closed: the endpoint stopped, its input ended, or its
32 /// output failed earlier. Nothing more can be sent.
33 Closed,
34 /// Outgoing `params` must be an array, an object, or `null` (sent as no
35 /// params); this was another kind of value. Nothing was sent.
36 InvalidParams(Kind),
37 /// The request was already answered (the peer cancelled it, or the
38 /// connection answered it for a panicking handler). This reply was not
39 /// sent.
40 AlreadyAnswered,
41}
42
43impl fmt::Display for Error {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 Error::Io(e) => write!(f, "the transport failed: {e}"),
47 Error::Frame(e) => write!(f, "the input lost its framing: {e}"),
48 Error::Closed => f.write_str("the connection is closed"),
49 Error::InvalidParams(kind) => write!(
50 f,
51 "params must be an array, an object, or null, not {} {kind}",
52 if matches!(kind, Kind::Array | Kind::Object) {
53 "an"
54 } else {
55 "a"
56 }
57 ),
58 Error::AlreadyAnswered => f.write_str("the request was already answered"),
59 }
60 }
61}
62
63impl std::error::Error for Error {
64 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65 match self {
66 Error::Io(e) => Some(e),
67 Error::Frame(e) => Some(e),
68 _ => None,
69 }
70 }
71}
72
73impl From<io::Error> for Error {
74 fn from(e: io::Error) -> Self {
75 Error::Io(e)
76 }
77}
78
79impl From<FrameError> for Error {
80 fn from(e: FrameError) -> Self {
81 Error::Frame(e)
82 }
83}
84
85impl From<Error> for ErrorObject {
86 /// An `-32603` internal error saying what failed, so a handler can apply
87 /// `?` to a send through its [`Context`](crate::Context).
88 ///
89 /// # Examples
90 ///
91 /// ```
92 /// use rpc_io::{Error, ErrorCode, ErrorObject};
93 ///
94 /// let e = ErrorObject::from(Error::Closed);
95 /// assert_eq!(e.code(), ErrorCode::INTERNAL_ERROR);
96 /// assert_eq!(e.message(), "the connection is closed");
97 /// ```
98 fn from(error: Error) -> Self {
99 ErrorObject::internal_error(error.to_string())
100 }
101}
102
103/// Why an outgoing request produced no result.
104///
105/// Every request ends in exactly one outcome: its result, or one of these.
106///
107/// # Examples
108///
109/// ```
110/// use rpc_io::{CallError, ErrorObject};
111///
112/// let e = CallError::Rejected(ErrorObject::method_not_found("x"));
113/// assert_eq!(e.to_string(), "the peer answered with an error: method not found: `x` (code -32601)");
114/// assert_eq!(CallError::TimedOut.to_string(), "the request timed out");
115/// ```
116#[derive(Clone, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum CallError {
119 /// The peer answered with this error.
120 Rejected(ErrorObject),
121 /// The peer's answer was not a valid response; this describes how.
122 InvalidResponse(ErrorObject),
123 /// The deadline passed without an answer. The peer was told to cancel.
124 TimedOut,
125 /// The request was cancelled (by [`Call::cancel`](crate::Call::cancel), a
126 /// [`Canceller`](crate::Canceller), or because the gate's opening request
127 /// failed before it was sent).
128 Cancelled,
129 /// More requests were outstanding than [`Config::max_pending`](crate::Config)
130 /// allows and this was the oldest. The peer was told to cancel.
131 Evicted,
132 /// The connection closed before an answer arrived.
133 Closed,
134 /// Waiting here would block the thread that reads the answer: a handler
135 /// cannot wait for a request it sent. Use [`Call::try_wait`](crate::Call::try_wait)
136 /// later, or wait on another thread.
137 WouldDeadlock,
138}
139
140impl fmt::Display for CallError {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 match self {
143 CallError::Rejected(e) => write!(f, "the peer answered with an error: {e}"),
144 CallError::InvalidResponse(e) => write!(f, "the peer's answer was invalid: {e}"),
145 CallError::TimedOut => f.write_str("the request timed out"),
146 CallError::Cancelled => f.write_str("the request was cancelled"),
147 CallError::Evicted => {
148 f.write_str("the request was dropped: too many requests were outstanding")
149 }
150 CallError::Closed => f.write_str("the connection closed before an answer arrived"),
151 CallError::WouldDeadlock => {
152 f.write_str("waiting would block the endpoint's own thread, which reads the answer")
153 }
154 }
155 }
156}
157
158impl std::error::Error for CallError {}