use crate::{RawJson, ReceiveSeq, RequestId, SessionKey, Submission};
use std::{fmt, sync::Arc};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidArgument,
NoRuntime,
Encode,
Decode,
Protocol {
code: i32,
message: String,
data: Option<RawJson>,
},
Timeout,
ResourceLimit {
resource: &'static str,
},
AdmissionFull,
IdExhausted,
SessionClosed,
SessionIdRetired,
EventBufferFull,
InvalidMessage,
ResponseSessionMismatch,
Transport,
ConnectionClosed,
DriverFailed,
}
#[derive(Clone, Debug)]
pub struct RequestContext {
pub method: String,
pub request_id: Option<RequestId>,
pub session_key: SessionKey,
pub submission: Submission,
pub receive_seq: Option<ReceiveSeq>,
}
#[derive(Clone)]
pub struct Error {
pub kind: ErrorKind,
pub context: Option<Box<RequestContext>>,
source: Option<Arc<dyn std::error::Error + Send + Sync>>,
frame: Option<crate::raw::Frame>,
}
impl Error {
pub fn new(kind: ErrorKind) -> Self {
Self {
kind,
context: None,
source: None,
frame: None,
}
}
pub fn with_source(
kind: ErrorKind,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
Self {
kind,
context: None,
source: Some(Arc::new(source)),
frame: None,
}
}
pub(crate) fn retain_frame(&mut self, frame: crate::raw::Frame) {
self.frame = Some(frame);
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("kind", &self.kind)
.field("context", &self.context)
.finish_non_exhaustive()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CDP 通信错误:{:?}", self.kind)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|s| s.as_ref() as _)
}
}