1use crate::{RawJson, ReceiveSeq, RequestId, SessionKey, Submission};
2use std::{fmt, sync::Arc};
3pub type Result<T> = std::result::Result<T, Error>;
5#[derive(Clone, Debug)]
7#[non_exhaustive]
8pub enum ErrorKind {
9 InvalidArgument,
11 NoRuntime,
13 Encode,
15 Decode,
17 Protocol {
19 code: i32,
21 message: String,
23 data: Option<RawJson>,
25 },
26 Timeout,
28 ResourceLimit {
30 resource: &'static str,
32 },
33 AdmissionFull,
35 IdExhausted,
37 SessionClosed,
39 SessionIdRetired,
41 EventBufferFull,
43 InvalidMessage,
45 ResponseSessionMismatch,
51 Transport,
53 ConnectionClosed,
55 DriverFailed,
57}
58#[derive(Clone, Debug)]
60pub struct RequestContext {
61 pub method: String,
63 pub request_id: Option<RequestId>,
65 pub session_key: SessionKey,
67 pub submission: Submission,
69 pub receive_seq: Option<ReceiveSeq>,
71}
72#[derive(Clone)]
74pub struct Error {
75 pub kind: ErrorKind,
77 pub context: Option<Box<RequestContext>>,
79 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
80 frame: Option<crate::raw::Frame>,
81}
82impl Error {
83 pub fn new(kind: ErrorKind) -> Self {
90 Self {
91 kind,
92 context: None,
93 source: None,
94 frame: None,
95 }
96 }
97 pub fn with_source(
104 kind: ErrorKind,
105 source: impl std::error::Error + Send + Sync + 'static,
106 ) -> Self {
107 Self {
108 kind,
109 context: None,
110 source: Some(Arc::new(source)),
111 frame: None,
112 }
113 }
114 pub(crate) fn retain_frame(&mut self, frame: crate::raw::Frame) {
117 self.frame = Some(frame);
118 }
119}
120impl fmt::Debug for Error {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("Error")
123 .field("kind", &self.kind)
124 .field("context", &self.context)
125 .finish_non_exhaustive()
126 }
127}
128impl fmt::Display for Error {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 write!(f, "CDP 通信错误:{:?}", self.kind)
131 }
132}
133impl std::error::Error for Error {
134 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
135 self.source.as_ref().map(|s| s.as_ref() as _)
136 }
137}