charon_error/errors/string_error.rs
1use std::{error::Error, fmt::Display};
2
3/// A simple error type that wraps a string message.
4///
5/// Use this when you need a quick error without defining a custom error type.
6/// Works with [`ErrorReport`](crate::ErrorReport) and [`ResultExt`](crate::ResultExt).
7///
8/// # Example
9///
10/// ```rust
11/// use charon_error::StringError;
12///
13/// let err = StringError::new("something went wrong");
14/// assert_eq!(err.message, "something went wrong");
15/// ```
16#[derive(Debug, Default, Clone)]
17pub struct StringError {
18 /// The error message text.
19 pub message: String,
20}
21
22impl StringError {
23 /// Create a new `StringError` from anything that converts to `String`.
24 #[must_use]
25 pub fn new<S: Into<String>>(message: S) -> Self {
26 Self {
27 message: message.into(),
28 }
29 }
30
31 /// Create a `StringError` from any existing error, capturing its display text.
32 #[must_use]
33 pub fn from_error<E: Error + Display>(err: E) -> Self {
34 Self {
35 message: err.to_string(),
36 }
37 }
38}
39
40impl Error for StringError {}
41
42impl Display for StringError {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 write!(f, "Error: `{}`", self.message,)
45 }
46}