Skip to main content

egui_pop_model/commands/
error.rs

1//! A command's failure, structured: what failed in the user's words, why,
2//! what to do, and the technical chain.
3
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use crate::notice::{Notice, Origin as NoticeOrigin};
9
10/// Why a command failed, for people and for the record.
11///
12/// A handler that knows what to tell the user builds one
13/// ([`CommandError::new`], then [`reason`](Self::reason),
14/// [`hint`](Self::hint), [`details`](Self::details)); its `user` mark
15/// says the headline is in the user's words. A bare text (`String`,
16/// `&str`) or an error (`std::io::Error`, a boxed error, `anyhow`'s
17/// through [`CommandError::from_error`]) converts to one whose headline
18/// is that text and whose `user` mark is off: shown to the user, it gets
19/// a generic headline ("Export did not work") and the text as its
20/// details.
21///
22/// Its `Display` is the headline, then `: ` and the reason when there is
23/// one: a `CommandError` made from a text displays that text unchanged,
24/// so code that prints or compares the old `String` errors keeps working.
25///
26/// ```
27/// use egui_pop_model::commands::CommandError;
28///
29/// let e = CommandError::from("connect: No route to host");
30/// assert_eq!(e.to_string(), "connect: No route to host");
31/// assert!(!e.user);
32///
33/// let e = CommandError::new("cloudy was not added")
34///     .reason("The network found no route to it.")
35///     .hint("Check that cloudy is on and on the same network.")
36///     .details("connect 192.168.1.12:7443: No route to host (os error 113)");
37/// assert!(e.user);
38/// assert_eq!(e.to_string(), "cloudy was not added: The network found no route to it.");
39/// ```
40///
41/// <div class="warning">Experimental: may change in any release
42/// (docs/stability.md).</div>
43#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct CommandError {
46    /// What failed: in the user's words when `user`, else the technical
47    /// text it was made from.
48    pub headline: String,
49    /// Why, in the user's words, when known.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub reason: Option<String>,
52    /// What the user can do about it.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub hint: Option<String>,
55    /// The technical chain (an error and its sources, one per line).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub details: Option<String>,
58    /// Whether the headline is written for the user (`false`: a technical
59    /// text, shown under a generic headline).
60    #[serde(default)]
61    pub user: bool,
62}
63
64/// A blank text is no text.
65fn some(text: impl Into<String>) -> Option<String> {
66    Some(text.into()).filter(|t| !t.trim().is_empty())
67}
68
69impl CommandError {
70    /// A failure told in the user's words.
71    pub fn new(headline: impl Into<String>) -> Self {
72        Self {
73            headline: headline.into(),
74            user: true,
75            ..Self::default()
76        }
77    }
78
79    /// A technical failure (`user` off): the text as its headline.
80    pub fn technical(text: impl Into<String>) -> Self {
81        Self {
82            headline: text.into(),
83            user: false,
84            ..Self::default()
85        }
86    }
87
88    /// An error and its sources: its text as the (technical) headline,
89    /// the whole chain, one per line, as the details.
90    pub fn from_error(err: &(dyn std::error::Error + 'static)) -> Self {
91        let mut chain = err.to_string();
92        let mut source = err.source();
93        while let Some(s) = source {
94            chain.push('\n');
95            chain.push_str(&s.to_string());
96            source = s.source();
97        }
98        let mut e = Self::technical(err.to_string());
99        if chain != e.headline {
100            e.details = Some(chain);
101        }
102        e
103    }
104
105    /// Why (left out when blank).
106    #[must_use]
107    pub fn reason(mut self, reason: impl Into<String>) -> Self {
108        self.reason = some(reason);
109        self
110    }
111
112    /// What to do (left out when blank).
113    #[must_use]
114    pub fn hint(mut self, hint: impl Into<String>) -> Self {
115        self.hint = some(hint);
116        self
117    }
118
119    /// The technical chain (left out when blank).
120    #[must_use]
121    pub fn details(mut self, details: impl Into<String>) -> Self {
122        self.details = some(details);
123        self
124    }
125
126    /// The error notice it gives, from the user's own action: its
127    /// headline, reason, hint and details when `user`; otherwise
128    /// `generic` as the headline and the technical text (with its
129    /// details) as the details.
130    pub fn to_notice(&self, generic: impl Into<String>) -> Notice {
131        let n = if self.user {
132            let mut n = Notice::error(self.headline.clone());
133            if let Some(r) = &self.reason {
134                n = n.reason(r.clone());
135            }
136            if let Some(h) = &self.hint {
137                n = n.hint(h.clone());
138            }
139            if let Some(d) = &self.details {
140                n = n.details(d.clone());
141            }
142            n
143        } else {
144            let mut details = self.headline.clone();
145            if let Some(d) = self.details.as_ref().filter(|d| **d != self.headline) {
146                details.push('\n');
147                details.push_str(d);
148            }
149            let mut n = Notice::error(generic).details(details);
150            if let Some(r) = &self.reason {
151                n = n.reason(r.clone());
152            }
153            if let Some(h) = &self.hint {
154                n = n.hint(h.clone());
155            }
156            n
157        };
158        n.origin(NoticeOrigin::User)
159    }
160}
161
162impl fmt::Display for CommandError {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.write_str(&self.headline)?;
165        if let Some(r) = &self.reason {
166            write!(f, ": {r}")?;
167        }
168        Ok(())
169    }
170}
171
172impl From<String> for CommandError {
173    fn from(text: String) -> Self {
174        Self::technical(text)
175    }
176}
177
178impl From<&str> for CommandError {
179    fn from(text: &str) -> Self {
180        Self::technical(text)
181    }
182}
183
184impl From<&String> for CommandError {
185    fn from(text: &String) -> Self {
186        Self::technical(text.clone())
187    }
188}
189
190impl From<std::io::Error> for CommandError {
191    fn from(err: std::io::Error) -> Self {
192        Self::from_error(&err)
193    }
194}
195
196impl From<serde_json::Error> for CommandError {
197    fn from(err: serde_json::Error) -> Self {
198        Self::from_error(&err)
199    }
200}
201
202impl From<Box<dyn std::error::Error + Send + Sync>> for CommandError {
203    /// A boxed error (`anyhow::Error` converts to one with `.into()`).
204    fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
205        Self::from_error(&*err)
206    }
207}
208
209impl From<Box<dyn std::error::Error>> for CommandError {
210    fn from(err: Box<dyn std::error::Error>) -> Self {
211        Self::from_error(&*err)
212    }
213}
214
215impl From<CommandError> for String {
216    /// Its `Display`: where a command's result is still a `String`.
217    fn from(err: CommandError) -> Self {
218        err.to_string()
219    }
220}