1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243// Copyright 2024 Heath Stewart.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
//! Error handling for this crate.
use std::{
borrow::{Borrow, Cow},
fmt,
};
/// A `Result` specific to this crate.
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
InvalidData,
Io,
Other,
NotFound,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// cspell:ignore errno
match self {
ErrorKind::InvalidData => f.write_str("InvalidData"),
ErrorKind::Io => f.write_str("Io"),
ErrorKind::Other => f.write_str("Other"),
ErrorKind::NotFound => f.write_str("NotFound"),
}
}
}
/// Error information for this crate.
#[derive(Debug)]
pub struct Error {
repr: Repr,
}
impl Error {
/// Constructs a new `Error` boxing another [`std::error::Error`].
pub fn new<E>(kind: ErrorKind, error: E) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Self {
repr: Repr::Custom(Custom {
kind,
error: error.into(),
}),
}
}
/// The [`ErrorKind`] of this `Error`.
pub fn kind(&self) -> &ErrorKind {
match &self.repr {
Repr::Simple(kind)
| Repr::SimpleMessage(kind, ..)
| Repr::Custom(Custom { kind, .. })
| Repr::CustomMessage(Custom { kind, .. }, ..) => kind,
}
}
/// The message provided when this `Error` was constructed, or `None`.
pub fn message(&self) -> Option<&str> {
match &self.repr {
Repr::SimpleMessage(_, message) | Repr::CustomMessage(_, message) => {
Some(message.borrow())
}
_ => None,
}
}
/// Create an `Error` with a message.
#[must_use]
pub fn with_message<C>(kind: ErrorKind, message: C) -> Self
where
C: Into<Cow<'static, str>>,
{
Self {
repr: Repr::SimpleMessage(kind, message.into()),
}
}
/// Create an `Error` using a function to return a message.
#[must_use]
pub fn with_message_fn<F, C>(kind: ErrorKind, message: F) -> Self
where
Self: Sized,
F: FnOnce() -> C,
C: Into<Cow<'static, str>>,
{
Self::with_message(kind, message())
}
/// Create an `Error` containing another error and a message.
#[must_use]
pub fn with_error<E, C>(kind: ErrorKind, error: E, message: C) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
C: Into<Cow<'static, str>>,
{
Self {
repr: Repr::CustomMessage(
Custom {
kind,
error: error.into(),
},
message.into(),
),
}
}
/// Create an `Error` containing another error and using a function to return a message.
#[must_use]
pub fn with_error_fn<E, F, C>(kind: ErrorKind, error: E, message: F) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
F: FnOnce() -> C,
C: Into<Cow<'static, str>>,
{
Self::with_error(kind, error, message())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.repr {
Repr::Simple(kind) => write!(f, "{kind}"),
Repr::SimpleMessage(_, message) => write!(f, "{message}"),
Repr::Custom(Custom { error, .. }) => write!(f, "{error}"),
Repr::CustomMessage(_, message) => write!(f, "{message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.repr {
Repr::Custom(Custom { error, .. }) | Repr::CustomMessage(Custom { error, .. }, ..) => {
Some(&**error)
}
_ => None,
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self {
repr: Repr::Simple(kind),
}
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
match error.kind() {
std::io::ErrorKind::NotFound => Self::new(ErrorKind::NotFound, error),
_ => Self::new(ErrorKind::Io, error),
}
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::new(ErrorKind::InvalidData, error)
}
}
impl From<dotenvy::Error> for Error {
fn from(error: dotenvy::Error) -> Self {
if error.not_found() {
return Self::new(ErrorKind::NotFound, error);
}
Self::new(ErrorKind::Io, error)
}
}
#[derive(Debug)]
enum Repr {
Simple(ErrorKind),
SimpleMessage(ErrorKind, Cow<'static, str>),
Custom(Custom),
CustomMessage(Custom, Cow<'static, str>),
}
#[derive(Debug)]
struct Custom {
kind: ErrorKind,
error: Box<dyn std::error::Error + Send + Sync>,
}
/// Extension methods for [`std::result::Result`].
pub trait ResultExt<T>: private::Sealed {
/// Create an [`Error`] containing another error with an [`ErrorKind`].
fn with_kind(self, kind: ErrorKind) -> Result<T>;
/// Create an [`Error`] containing another error with an [`ErrorKind`] and message.
fn with_context<C>(self, kind: ErrorKind, message: C) -> Result<T>
where
Self: Sized,
C: Into<Cow<'static, str>>;
/// Create an [`Error`] containing another error with an [`ErrorKind`] and a function that returns a message.
fn with_context_fn<F, C>(self, kind: ErrorKind, f: F) -> Result<T>
where
Self: Sized,
F: FnOnce() -> C,
C: Into<Cow<'static, str>>;
}
impl<T, E> ResultExt<T> for std::result::Result<T, E>
where
E: std::error::Error + Send + Sync + 'static,
{
fn with_kind(self, kind: ErrorKind) -> Result<T> {
self.map_err(|err| Error::new(kind, err))
}
fn with_context<C>(self, kind: ErrorKind, message: C) -> Result<T>
where
Self: Sized,
C: Into<Cow<'static, str>>,
{
self.map_err(|err| Error::with_error(kind, Box::new(err), message))
}
fn with_context_fn<F, C>(self, kind: ErrorKind, f: F) -> Result<T>
where
Self: Sized,
F: FnOnce() -> C,
C: Into<Cow<'static, str>>,
{
self.with_context(kind, f())
}
}
mod private {
pub trait Sealed {}
impl<T, E> Sealed for std::result::Result<T, E> where E: std::error::Error + Send + Sync + 'static {}
}