cot 0.5.0

The Rust web framework for lazy developers.
Documentation
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::error::Error as StdError;
use std::fmt::Display;
use std::ops::Deref;

use derive_more::with_trait::Debug;

use crate::StatusCode;
// Need to rename Backtrace to CotBacktrace, because otherwise it triggers special behavior
// in the thiserror library
use crate::error::backtrace::{__cot_create_backtrace, Backtrace as CotBacktrace};
use crate::error::not_found::NotFound;

/// An error that can occur while using Cot.
pub struct Error {
    repr: Box<ErrorImpl>,
}

impl Error {
    /// Create a new error with a custom error message or error type.
    ///
    /// This method is used to create a new error that does not have a specific
    /// HTTP status code associated with it. If in the chain of `Error` sources
    /// there is an error with a status code, it will be used instead. If not,
    /// the default status code of 500 Internal Server Error will be used.
    ///
    /// To get the first instance of `Error` in the chain that has a
    /// status code, use the [`Error::inner`] method.
    #[must_use]
    pub fn wrap<E>(error: E) -> Self
    where
        E: Into<Box<dyn StdError + Send + Sync + 'static>>,
    {
        Self {
            repr: Box::new(ErrorImpl {
                inner: error.into(),
                status_code: None,
                backtrace: __cot_create_backtrace(),
            }),
        }
    }

    /// Create a new error with a custom error message or error type.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::Error;
    ///
    /// let error = Error::custom("An error occurred");
    /// let error = Error::custom(std::io::Error::new(
    ///     std::io::ErrorKind::Other,
    ///     "An error occurred",
    /// ));
    /// ```
    #[deprecated(
        note = "Use `cot::Error::internal` or `cot::Error::with_status` instead",
        since = "0.4.0"
    )]
    #[must_use]
    pub fn custom<E>(error: E) -> Self
    where
        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
    {
        Self::internal(error)
    }

    /// Create a new error with a custom error message or error type.
    ///
    /// The error will be associated with a 500 Internal Server Error
    /// status code, which is the default for unexpected errors.
    ///
    /// If you want to create an error with a different status code,
    /// use [`Error::with_status`].
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::Error;
    ///
    /// let error = Error::internal("An error occurred");
    /// let error = Error::internal(std::io::Error::new(
    ///     std::io::ErrorKind::Other,
    ///     "An error occurred",
    /// ));
    /// ```
    #[must_use]
    pub fn internal<E>(error: E) -> Self
    where
        E: Into<Box<dyn StdError + Send + Sync + 'static>>,
    {
        Self::with_status(error, StatusCode::INTERNAL_SERVER_ERROR)
    }

    /// Create a new error with a custom error message or error type and a
    /// specific HTTP status code.
    ///
    /// This method allows you to create an error with a custom status code,
    /// which will be returned in the HTTP response. This is useful when you
    /// want to return specific HTTP status codes like 400 Bad Request, 403
    /// Forbidden, etc.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::{Error, StatusCode};
    ///
    /// // Create a 400 Bad Request error
    /// let error = Error::with_status("Invalid input", StatusCode::BAD_REQUEST);
    ///
    /// // Create a 403 Forbidden error
    /// let error = Error::with_status("Access denied", StatusCode::FORBIDDEN);
    /// ```
    #[must_use]
    pub fn with_status<E>(error: E, status_code: StatusCode) -> Self
    where
        E: Into<Box<dyn StdError + Send + Sync + 'static>>,
    {
        let error = Self {
            repr: Box::new(ErrorImpl {
                inner: error.into(),
                status_code: Some(status_code),
                backtrace: __cot_create_backtrace(),
            }),
        };
        Self::wrap(WithStatusCode(error))
    }

    /// Create a new admin panel error with a custom error message or error
    /// type.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::Error;
    ///
    /// let error = Error::admin("An error occurred");
    /// let error = Error::admin(std::io::Error::new(
    ///     std::io::ErrorKind::Other,
    ///     "An error occurred",
    /// ));
    /// ```
    #[deprecated(
        note = "Use `cot::Error::wrap`, `cot::Error::internal`, or \
        `cot::Error::with_status` directly instead",
        since = "0.4.0"
    )]
    pub fn admin<E>(error: E) -> Self
    where
        E: Into<Box<dyn StdError + Send + Sync + 'static>>,
    {
        Self::internal(error)
    }

    /// Create a new "404 Not Found" error without a message.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::Error;
    ///
    /// let error = Error::not_found();
    /// ```
    #[must_use]
    #[deprecated(
        note = "Use `cot::Error::from(cot::error::NotFound::new())` instead",
        since = "0.4.0"
    )]
    pub fn not_found() -> Self {
        Self::from(NotFound::new())
    }

    /// Create a new "404 Not Found" error with a message.
    ///
    /// Note that the message is only displayed when Cot's debug mode is
    /// enabled. It will not be exposed to the user in production.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::Error;
    ///
    /// let id = 123;
    /// let error = Error::not_found_message(format!("User with id={id} not found"));
    /// ```
    #[must_use]
    #[deprecated(
        note = "Use `cot::Error::from(cot::error::NotFound::with_message())` instead",
        since = "0.4.0"
    )]
    pub fn not_found_message(message: String) -> Self {
        Self::from(NotFound::with_message(message))
    }

    /// Returns the HTTP status code associated with this error.
    ///
    /// This method returns the appropriate HTTP status code that should be
    /// sent in the response when this error occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::{Error, StatusCode};
    ///
    /// let error = Error::internal("Something went wrong");
    /// assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    ///
    /// let error = Error::with_status("Bad request", StatusCode::BAD_REQUEST);
    /// assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
    /// ```
    #[must_use]
    pub fn status_code(&self) -> StatusCode {
        self.inner()
            .repr
            .status_code
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
    }

    #[must_use]
    pub(crate) fn backtrace(&self) -> &CotBacktrace {
        &self.repr.backtrace
    }

    /// Returns a reference to inner `Error`, if `self` is wrapping a wrapper.
    /// Otherwise, it returns `self`.
    ///
    /// If this error is a wrapper around another `Error`, this method will
    /// return the inner `Error` that has a specific status code.
    ///
    /// This is useful for extracting the original error that caused the
    /// error, especially when dealing with errors that may have been
    /// wrapped multiple times in the error chain (e.g., by middleware or
    /// other error handling logic). You should use this method most
    /// of the time when you need to access the original error.
    ///
    /// # See also
    ///
    /// - [`Error::wrap`]
    #[must_use]
    pub fn inner(&self) -> &Self {
        let mut error: &dyn StdError = self;
        while let Some(inner) = error.source() {
            if let Some(error) = inner.downcast_ref::<Self>()
                && !error.is_wrapper()
            {
                return error;
            }
            error = inner;
        }
        self
    }

    /// Returns `true` if this error is a wrapper around another error.
    ///
    /// In other words, this returns `true` if the error has been created
    /// with [`Error::wrap`], which means it does not have a specific
    /// HTTP status code associated with it. Otherwise, it returns `false`.
    #[must_use]
    pub fn is_wrapper(&self) -> bool {
        self.repr.status_code.is_none()
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.repr, f)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.repr.inner, f)
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.repr.inner.source()
    }
}

impl Deref for Error {
    type Target = dyn StdError + Send + Sync;

    fn deref(&self) -> &Self::Target {
        &*self.repr.inner
    }
}

#[derive(Debug)]
struct ErrorImpl {
    inner: Box<dyn StdError + Send + Sync>,
    status_code: Option<StatusCode>,
    #[debug(skip)]
    backtrace: CotBacktrace,
}

/// Indicates that the inner `Error` has a status code associated with it.
///
/// This is important, as we need to have this `Error` to be returned
/// by `std::error::Error::source` to be able to extract the status code.
#[derive(Debug)]
struct WithStatusCode(Error);

impl Display for WithStatusCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl StdError for WithStatusCode {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(&self.0)
    }
}

impl From<Error> for askama::Error {
    fn from(value: Error) -> Self {
        askama::Error::Custom(Box::new(value))
    }
}

macro_rules! impl_into_cot_error {
    ($error_ty:ty) => {
        impl From<$error_ty> for $crate::Error {
            fn from(err: $error_ty) -> Self {
                $crate::Error::internal(err)
            }
        }
    };
    ($error_ty:ty, $status_code:ident) => {
        impl From<$error_ty> for $crate::Error {
            fn from(err: $error_ty) -> Self {
                $crate::Error::with_status(err, $crate::StatusCode::$status_code)
            }
        }
    };
}
pub(crate) use impl_into_cot_error;

#[derive(Debug, thiserror::Error)]
#[error("failed to render template: {0}")]
struct TemplateRender(#[from] askama::Error);
impl_into_cot_error!(TemplateRender);
impl From<askama::Error> for Error {
    fn from(err: askama::Error) -> Self {
        Error::from(TemplateRender(err))
    }
}

#[derive(Debug, thiserror::Error)]
#[error("error while accessing the session object")]
struct SessionAccess(#[from] tower_sessions::session::Error);
impl_into_cot_error!(SessionAccess);
impl From<tower_sessions::session::Error> for Error {
    fn from(err: tower_sessions::session::Error) -> Self {
        Error::from(SessionAccess(err))
    }
}

#[cfg(test)]
mod tests {
    use serde::ser::Error as _;

    use super::*;

    #[test]
    fn error_new() {
        let inner = std::io::Error::other("server error");
        let error = Error::wrap(inner);

        assert!(StdError::source(&error).is_none());
        assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn error_display() {
        let inner = std::io::Error::other("server error");
        let error = Error::internal(inner);

        let display = format!("{error}");

        assert_eq!(display, "server error");
    }

    #[test]
    fn error_wrap_and_is_wrapper() {
        let inner = std::io::Error::other("wrapped");
        let error = Error::wrap(inner);

        assert!(error.is_wrapper());
        assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn error_with_status_propagation() {
        let error = Error::with_status("bad request", StatusCode::BAD_REQUEST);
        assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
        // wrapping again should not override the status code
        let wrapped = Error::wrap(error);

        assert_eq!(wrapped.status_code(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn error_inner_returns_original() {
        let error = Error::with_status("bad request", StatusCode::BAD_REQUEST);
        let wrapped = Error::wrap(error);

        assert_eq!(wrapped.inner().status_code(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn error_inner_multiple_wrapped() {
        let error = Error::with_status("bad request", StatusCode::BAD_REQUEST);
        let wrapped = Error::wrap(error);
        let wrapped_twice = Error::wrap(wrapped);
        let wrapped_thrice = Error::wrap(wrapped_twice);

        assert_eq!(wrapped_thrice.to_string(), "bad request");
        assert!(wrapped_thrice.source().is_some());
        assert!(wrapped_thrice.source().unwrap().source().is_none());
        assert_eq!(
            wrapped_thrice.inner().status_code(),
            StatusCode::BAD_REQUEST
        );
    }

    #[test]
    fn error_deref_to_inner() {
        let error = Error::internal("deref test");
        let msg = format!("{}", &*error);

        assert_eq!(msg, "deref test");
    }

    #[test]
    fn error_from_template_render() {
        let askama_err = askama::Error::Custom(Box::new(std::io::Error::other("fail")));
        let error: Error = askama_err.into();

        assert!(error.to_string().contains("failed to render template"));
    }

    #[test]
    fn error_from_session_access() {
        let session_err =
            tower_sessions::session::Error::SerdeJson(serde_json::Error::custom("session error"));

        let error: Error = session_err.into();

        assert!(
            error
                .to_string()
                .contains("error while accessing the session object")
        );
    }
}