Debian Codegraph @

src/raw/error.rs

raw
1 use std::str::Utf8Error;
2
3 use crate::spec::ElementType;
4
5 /// An error that occurs when attempting to parse raw BSON bytes.
6 #[derive(Debug, PartialEq, Clone)]
7 #[non_exhaustive]
8 pub struct Error {
9 /// The type of error that was encountered.
10 pub kind: ErrorKind,
11
12 /// They key associated with the error, if any.
13 pub(crate) key: Option<String>,
14 }
15
16 impl Error {
17 pub(crate) fn new_with_key(key: impl Into<String>, kind: ErrorKind) -> Self {
18 Self {
19 kind,
20 key: Some(key.into()),
21 }
22 }
23
24 pub(crate) fn new_without_key(kind: ErrorKind) -> Self {
25 Self { key: None, kind }
26 }
27
28 pub(crate) fn with_key(mut self, key: impl AsRef<str>) -> Self {
29 self.key = Some(key.as_ref().to_string());
30 self
31 }
32
33 /// The key at which the error was encountered, if any.
34 pub fn key(&self) -> Option<&str> {
35 self.key.as_deref()
36 }
37 }
38
39 /// The different categories of errors that can be returned when reading from raw BSON.
40 #[derive(Clone, Debug, PartialEq)]
41 #[non_exhaustive]
42 pub enum ErrorKind {
43 /// A BSON value did not fit the proper format.
44 #[non_exhaustive]
45 MalformedValue { message: String },
46
47 /// Improper UTF-8 bytes were found when proper UTF-8 was expected.
48 Utf8EncodingError(Utf8Error),
49 }
50
51 impl ErrorKind {
52 pub(crate) fn new_malformed(e: impl ToString) -> Self {
53 ErrorKind::MalformedValue {
54 message: e.to_string(),
55 }
56 }
57 }
58
59 impl std::fmt::Display for Error {
60 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
61 let p = self
62 .key
63 .as_ref()
64 .map(|k| format!("error at key \"{}\": ", k));
65
66 let prefix = p.as_ref().map_or("", |p| p.as_str());
67
68 match &self.kind {
69 ErrorKind::MalformedValue { message } => {
70 write!(f, "{}malformed value: {:?}", prefix, message)
71 }
72 ErrorKind::Utf8EncodingError(e) => write!(f, "{}utf-8 encoding error: {}", prefix, e),
73 }
74 }
75 }
76
77 impl std::error::Error for Error {}
78
79 pub type Result<T> = std::result::Result<T, Error>;
80
81 /// Execute the provided closure, mapping the key of the returned error (if any) to the provided
82 /// key.
83 pub(crate) fn try_with_key<G, F: FnOnce() -> Result<G>>(key: impl AsRef<str>, f: F) -> Result<G> {
84 f().map_err(|e| e.with_key(key))
85 }
86
87 pub type ValueAccessResult<T> = std::result::Result<T, ValueAccessError>;
88
89 /// Error to indicate that either a value was empty or it contained an unexpected
90 /// type, for use with the direct getters (e.g. [`crate::RawDocument::get_str`]).
91 #[derive(Debug, PartialEq, Clone)]
92 #[non_exhaustive]
93 pub struct ValueAccessError {
94 /// The type of error that was encountered.
95 pub kind: ValueAccessErrorKind,
96
97 /// The key at which the error was encountered.
98 pub(crate) key: String,
99 }
100
101 impl ValueAccessError {
102 /// The key at which the error was encountered.
103 pub fn key(&self) -> &str {
104 self.key.as_str()
105 }
106 }
107
108 /// The type of error encountered when using a direct getter (e.g. [`crate::RawDocument::get_str`]).
109 #[derive(Debug, PartialEq, Clone)]
110 #[non_exhaustive]
111 pub enum ValueAccessErrorKind {
112 /// Cannot find the expected field with the specified key
113 NotPresent,
114
115 /// Found a Bson value with the specified key, but not with the expected type
116 #[non_exhaustive]
117 UnexpectedType {
118 /// The type that was expected.
119 expected: ElementType,
120
121 /// The actual type that was encountered.
122 actual: ElementType,
123 },
124
125 /// An error was encountered attempting to decode the document.
126 InvalidBson(super::Error),
127 }
128
129 impl std::fmt::Display for ValueAccessError {
130 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
131 let prefix = format!("error at key: \"{}\": ", self.key);
132
133 match &self.kind {
134 ValueAccessErrorKind::UnexpectedType { actual, expected } => write!(
135 f,
136 "{} unexpected element type: {:?}, expected: {:?}",
137 prefix, actual, expected
138 ),
139 ValueAccessErrorKind::InvalidBson(error) => {
140 write!(f, "{}: {}", prefix, error)
141 }
142 ValueAccessErrorKind::NotPresent => write!(f, "{}value not present", prefix),
143 }
144 }
145 }
146
147 impl std::error::Error for ValueAccessError {}