use std::fmt;
use crate::api_version::ApiVersion;
use crate::frame::FrameError;
use crate::wire::v1::{self, ErrorCode};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallError {
pub code: ErrorCode,
pub message: String,
}
impl CallError {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub fn failed(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Failed, message)
}
pub fn cancelled() -> Self {
Self::new(ErrorCode::Cancelled, "the call was cancelled")
}
pub(crate) fn disconnected() -> Self {
Self::failed("the host closed the connection")
}
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CallError {}
impl From<v1::Error> for CallError {
fn from(error: v1::Error) -> Self {
let code = match ErrorCode::try_from(error.code) {
Ok(ErrorCode::Unspecified) | Err(_) => ErrorCode::Failed,
Ok(code) => code,
};
Self::new(code, error.message)
}
}
impl From<CallError> for v1::Error {
fn from(error: CallError) -> Self {
Self {
code: error.code.into(),
message: error.message,
}
}
}
#[derive(Debug)]
pub enum RunError {
Frame(FrameError),
NoHello,
IncompatibleApi {
host: ApiVersion,
},
Disconnected,
}
impl fmt::Display for RunError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Frame(error) => error.fmt(f),
Self::NoHello => f.write_str("the first message from the host was not `Hello`"),
Self::IncompatibleApi { host } => write!(
f,
"the host supplies the extension API version {host}, but this extension needs {}",
crate::ApiRequirement::from(ApiVersion::CURRENT)
),
Self::Disconnected => {
f.write_str("the host closed the stream and did not send a shutdown request")
}
}
}
}
impl std::error::Error for RunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Frame(error) => Some(error),
Self::NoHello | Self::IncompatibleApi { .. } | Self::Disconnected => None,
}
}
}
impl From<FrameError> for RunError {
fn from(error: FrameError) -> Self {
Self::Frame(error)
}
}