use std::{fmt, io};
use jsonx_lib::Kind;
use crate::{error_object::ErrorObject, framing::FrameError};
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Io(io::Error),
Frame(FrameError),
Closed,
InvalidParams(Kind),
AlreadyAnswered,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "the transport failed: {e}"),
Error::Frame(e) => write!(f, "the input lost its framing: {e}"),
Error::Closed => f.write_str("the connection is closed"),
Error::InvalidParams(kind) => write!(
f,
"params must be an array, an object, or null, not {} {kind}",
if matches!(kind, Kind::Array | Kind::Object) {
"an"
} else {
"a"
}
),
Error::AlreadyAnswered => f.write_str("the request was already answered"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
Error::Frame(e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
impl From<FrameError> for Error {
fn from(e: FrameError) -> Self {
Error::Frame(e)
}
}
impl From<Error> for ErrorObject {
fn from(error: Error) -> Self {
ErrorObject::internal_error(error.to_string())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CallError {
Rejected(ErrorObject),
InvalidResponse(ErrorObject),
TimedOut,
Cancelled,
Evicted,
Closed,
WouldDeadlock,
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CallError::Rejected(e) => write!(f, "the peer answered with an error: {e}"),
CallError::InvalidResponse(e) => write!(f, "the peer's answer was invalid: {e}"),
CallError::TimedOut => f.write_str("the request timed out"),
CallError::Cancelled => f.write_str("the request was cancelled"),
CallError::Evicted => {
f.write_str("the request was dropped: too many requests were outstanding")
}
CallError::Closed => f.write_str("the connection closed before an answer arrived"),
CallError::WouldDeadlock => {
f.write_str("waiting would block the endpoint's own thread, which reads the answer")
}
}
}
}
impl std::error::Error for CallError {}