human_errors/
description.rs

1use std::fmt;
2
3/// Generates an error with the given `message`.
4///
5/// Generates a [std::error::Error] compatible error for the given
6/// message. Can be used as the internal error for an [crate::Error].
7///
8/// # Examples
9/// ```
10/// use human_errors;
11///
12/// human_errors::user_with_internal(
13///   "We could not open the config file you provided.",
14///   "Make sure that the file exists and is readable by the application.",
15///   human_errors::detailed_message("ENOENT 2: No such file or directory")
16/// );
17/// ```
18pub fn detailed_message(message: &str) -> BasicInternalError {
19    message.into()
20}
21
22#[derive(Debug)]
23pub struct BasicInternalError {
24    message: String,
25}
26
27impl From<&str> for BasicInternalError {
28    fn from(s: &str) -> Self {
29        Self {
30            message: s.to_string(),
31        }
32    }
33}
34
35impl std::error::Error for BasicInternalError {}
36
37impl fmt::Display for BasicInternalError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{}", self.message)
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use crate::*;
47
48    #[test]
49    fn test_message_internal() {
50        assert_eq!(
51            user_with_internal(
52                "Something bad happened.",
53                "Avoid bad things happening in future",
54                detailed_message("You got rate limited")
55            )
56            .message(),
57            "Oh no! Something bad happened.\n\nThis was caused by:\n - You got rate limited\n\nTo try and fix this, you can:\n - Avoid bad things happening in future"
58        );
59
60        assert_eq!(
61            system_with_internal(
62                "Something bad happened.",
63                "Avoid bad things happening in future",
64                detailed_message("You got rate limited")
65            )
66            .message(),
67            "Whoops! Something bad happened. (This isn't your fault)\n\nThis was caused by:\n - You got rate limited\n\nTo try and fix this, you can:\n - Avoid bad things happening in future"
68        );
69    }
70}