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