http_problem/
commons.rs

1use std::fmt;
2
3use crate::{custom::StatusCode, CowStr};
4
5/// An error emitted when an assertion failed to be satisfied.
6///
7/// Emitted by [`ensure!`].
8///
9/// [`ensure!`]: crate::ensure
10#[derive(Debug, Clone)]
11pub struct AssertionError {
12    msg: CowStr,
13}
14
15impl fmt::Display for AssertionError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        write!(f, "assertion failure: {}", self.msg)
18    }
19}
20
21impl std::error::Error for AssertionError {}
22
23impl AssertionError {
24    /// Message stored in this error.
25    #[inline(always)]
26    pub fn message(&self) -> &str {
27        &self.msg
28    }
29
30    #[doc(hidden)]
31    pub const fn new_static(msg: &'static str) -> Self {
32        Self {
33            msg: CowStr::Borrowed(msg),
34        }
35    }
36
37    #[doc(hidden)]
38    pub const fn new(msg: String) -> Self {
39        Self {
40            msg: CowStr::Owned(msg),
41        }
42    }
43}
44
45impl From<AssertionError> for crate::Problem {
46    #[track_caller]
47    fn from(err: AssertionError) -> Self {
48        Self::from_status(StatusCode::INTERNAL_SERVER_ERROR)
49            .with_detail("An unexpected error occurred")
50            .with_cause(err)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use crate::Problem;
58
59    #[test]
60    fn test_assert_static() {
61        let err = AssertionError::new_static("bla");
62        assert_eq!(err.message(), "bla");
63
64        let prb = Problem::from(err.clone());
65
66        assert_eq!(prb.status(), StatusCode::INTERNAL_SERVER_ERROR);
67        assert_ne!(prb.details(), err.message());
68    }
69
70    #[test]
71    fn test_assert_owned() {
72        let err = AssertionError::new("bla".to_string());
73        assert_eq!(err.message(), "bla");
74
75        let prb = Problem::from(err.clone());
76
77        assert_eq!(prb.status(), StatusCode::INTERNAL_SERVER_ERROR);
78        assert_ne!(prb.details(), err.message());
79    }
80}