changeset 76:e58d24849e82

Add Message::set_error to quickly answer a question with an error.
author Paul Fisher <paul@pfish.zone>
date Sat, 07 Jun 2025 18:55:27 -0400
parents c30811b4afae
children 351bdc13005e
files src/conv.rs
diffstat 1 files changed, 36 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/conv.rs	Fri Jun 06 22:35:08 2025 -0400
+++ b/src/conv.rs	Sat Jun 07 18:55:27 2025 -0400
@@ -12,6 +12,7 @@
 ///
 /// The data within each enum value is the prompt (or other information)
 /// that will be presented to the user.
+#[non_exhaustive]
 pub enum Message<'a> {
     MaskedPrompt(&'a MaskedPrompt<'a>),
     Prompt(&'a Prompt<'a>),
@@ -21,6 +22,41 @@
     ErrorMsg(&'a ErrorMsg<'a>),
 }
 
+impl Message<'_> {
+    /// Sets an error answer on this question, without having to inspect it.
+    ///
+    /// Use this as a default match case:
+    ///
+    /// ```
+    /// use nonstick::conv::{Message, QAndA};
+    /// use nonstick::ErrorCode;
+    ///
+    /// fn cant_respond(message: Message) {
+    ///     match message {
+    ///         Message::InfoMsg(i) => {
+    ///             eprintln!("fyi, {}", i.question());
+    ///             i.set_answer(Ok(()))
+    ///         }
+    ///         Message::ErrorMsg(e) => {
+    ///             eprintln!("ERROR: {}", e.question());
+    ///             e.set_answer(Ok(()))
+    ///         }
+    ///         // We can't answer any questions.
+    ///         other => other.set_error(ErrorCode::ConversationError),
+    ///     }
+    /// }
+    pub fn set_error(&self, err: ErrorCode) {
+        match self {
+            Message::MaskedPrompt(m) => m.set_answer(Err(err)),
+            Message::Prompt(m) => m.set_answer(Err(err)),
+            Message::RadioPrompt(m) => m.set_answer(Err(err)),
+            Message::BinaryPrompt(m) => m.set_answer(Err(err)),
+            Message::InfoMsg(m) => m.set_answer(Err(err)),
+            Message::ErrorMsg(m) => m.set_answer(Err(err)),
+        }
+    }
+}
+
 /// A question-and-answer pair that can be communicated in a [`Conversation`].
 ///
 /// The asking side creates a `QAndA`, then converts it to a [`Message`]