Skip to main content

turnloop_mongodb/
error.rs

1use bson::{Document, raw::RawDocument};
2use std::{borrow::Cow, fmt};
3pub type Result<T> = std::result::Result<T, Error>;
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum ErrorKind {
6    Parse,
7    Protocol,
8    Authentication,
9    Server,
10    BulkWrite,
11    Network,
12    Timeout,
13    WaitQueueTimeout,
14    ServerSelectionTimeout,
15    OperationTimeout,
16    PoolCleared,
17    PoolClosed,
18    InvalidArgument,
19    Cancelled,
20}
21#[derive(Clone, Debug)]
22pub struct Error {
23    pub kind: ErrorKind,
24    pub message: Cow<'static, str>,
25    pub code: Option<i32>,
26    pub code_name: Option<String>,
27    pub labels: Vec<String>,
28    /// Full owned server result only on failure, preserving writeErrors and errInfo.
29    pub response: Option<Box<Document>>,
30}
31impl Error {
32    pub fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Self {
33        Self {
34            kind,
35            message: message.into(),
36            code: None,
37            code_name: None,
38            labels: Vec::new(),
39            response: None,
40        }
41    }
42    pub fn protocol(message: &'static str) -> Self {
43        Self::new(ErrorKind::Protocol, message)
44    }
45    pub fn name(&self) -> &'static str {
46        match self.kind {
47            ErrorKind::Parse => "MongoParseError",
48            ErrorKind::Protocol => "MongoUnexpectedServerResponseError",
49            ErrorKind::Authentication | ErrorKind::Server => "MongoServerError",
50            ErrorKind::BulkWrite => "MongoBulkWriteError",
51            ErrorKind::Network => "MongoNetworkError",
52            ErrorKind::Timeout => "MongoNetworkTimeoutError",
53            ErrorKind::WaitQueueTimeout => "MongoWaitQueueTimeoutError",
54            ErrorKind::ServerSelectionTimeout => "MongoServerSelectionError",
55            ErrorKind::OperationTimeout => "MongoOperationTimeoutError",
56            ErrorKind::PoolCleared => "MongoPoolClearedError",
57            ErrorKind::PoolClosed => "MongoPoolClosedError",
58            ErrorKind::InvalidArgument => "MongoInvalidArgumentError",
59            ErrorKind::Cancelled => "MongoOperationTimeoutError",
60        }
61    }
62    pub fn has_label(&self, label: &str) -> bool {
63        self.labels.iter().any(|x| x == label)
64    }
65    pub fn from_response(raw: &RawDocument) -> Result<()> {
66        let ok = number(raw, "ok").unwrap_or(0.0) != 0.0;
67        let write = raw
68            .get("writeErrors")
69            .ok()
70            .flatten()
71            .and_then(|v| v.as_array())
72            .is_some_and(|a| a.into_iter().next().is_some());
73        let concern = raw
74            .get("writeConcernError")
75            .ok()
76            .flatten()
77            .and_then(|v| v.as_document());
78        if ok && !write && concern.is_none() {
79            return Ok(());
80        }
81        let doc: Document = raw
82            .try_into()
83            .map_err(|_| Self::protocol("Invalid BSON error response"))?;
84        let detail = if write {
85            doc.get_array("writeErrors")
86                .ok()
87                .and_then(|a| a.first())
88                .and_then(|v| v.as_document())
89                .unwrap_or(&doc)
90        } else {
91            doc.get_document("writeConcernError").unwrap_or(&doc)
92        };
93        let mut err = Self::new(
94            if write {
95                ErrorKind::BulkWrite
96            } else {
97                ErrorKind::Server
98            },
99            detail
100                .get_str("errmsg")
101                .unwrap_or("MongoDB command failed")
102                .to_owned(),
103        );
104        err.code = detail.get_i32("code").ok();
105        err.code_name = detail.get_str("codeName").ok().map(str::to_owned);
106        err.labels = doc
107            .get_array("errorLabels")
108            .ok()
109            .into_iter()
110            .flatten()
111            .filter_map(|b| b.as_str().map(str::to_owned))
112            .collect();
113        err.response = Some(Box::new(doc));
114        Err(err)
115    }
116}
117pub(crate) fn number(d: &RawDocument, k: &str) -> Option<f64> {
118    match d.get(k).ok().flatten()? {
119        bson::raw::RawBsonRef::Double(v) => Some(v),
120        bson::raw::RawBsonRef::Int32(v) => Some(f64::from(v)),
121        bson::raw::RawBsonRef::Int64(v) => Some(v as f64),
122        _ => None,
123    }
124}
125impl fmt::Display for Error {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        write!(f, "{}: {}", self.name(), self.message)
128    }
129}
130impl std::error::Error for Error {}