1use std::fmt;
4
5use crate::api_version::ApiVersion;
6use crate::frame::FrameError;
7use crate::wire::v1::{self, ErrorCode};
8
9#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct CallError {
16 pub code: ErrorCode,
18 pub message: String,
20}
21
22impl CallError {
23 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
25 Self {
26 code,
27 message: message.into(),
28 }
29 }
30
31 pub fn failed(message: impl Into<String>) -> Self {
33 Self::new(ErrorCode::Failed, message)
34 }
35
36 pub fn cancelled() -> Self {
39 Self::new(ErrorCode::Cancelled, "the call was cancelled")
40 }
41
42 pub(crate) fn disconnected() -> Self {
43 Self::failed("the host closed the connection")
44 }
45}
46
47impl fmt::Display for CallError {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str(&self.message)
50 }
51}
52
53impl std::error::Error for CallError {}
54
55impl From<v1::Error> for CallError {
56 fn from(error: v1::Error) -> Self {
57 let code = match ErrorCode::try_from(error.code) {
60 Ok(ErrorCode::Unspecified) | Err(_) => ErrorCode::Failed,
61 Ok(code) => code,
62 };
63 Self::new(code, error.message)
64 }
65}
66
67impl From<CallError> for v1::Error {
68 fn from(error: CallError) -> Self {
69 Self {
70 code: error.code.into(),
71 message: error.message,
72 }
73 }
74}
75
76#[derive(Debug)]
79pub enum RunError {
80 Frame(FrameError),
82 NoHello,
84 IncompatibleApi {
87 host: ApiVersion,
89 },
90 Disconnected,
92}
93
94impl fmt::Display for RunError {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 match self {
97 Self::Frame(error) => error.fmt(f),
98 Self::NoHello => f.write_str("the first message from the host was not `Hello`"),
99 Self::IncompatibleApi { host } => write!(
100 f,
101 "the host supplies the extension API version {host}, which this extension cannot use"
102 ),
103 Self::Disconnected => {
104 f.write_str("the host closed the stream and did not send a shutdown request")
105 }
106 }
107 }
108}
109
110impl std::error::Error for RunError {
111 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
112 match self {
113 Self::Frame(error) => Some(error),
114 Self::NoHello | Self::IncompatibleApi { .. } | Self::Disconnected => None,
115 }
116 }
117}
118
119impl From<FrameError> for RunError {
120 fn from(error: FrameError) -> Self {
121 Self::Frame(error)
122 }
123}