Skip to content

Commit

Permalink
feat(error): New error context API
Browse files Browse the repository at this point in the history
This is meant to replace `Error::info` as part of clap-rs#2628.
  • Loading branch information
epage committed Feb 3, 2022
1 parent d1a6cca commit cce2c68
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/error/context.rs
@@ -0,0 +1,17 @@
/// Semantics for a piece of error information
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContextKind {
/// An opaque message to the user
Custom,
}

/// A piece of error information
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContextValue {
/// [`ContextKind`] is self-sufficient, no additional information needed
None,
/// A single value
Value(String),
}
12 changes: 10 additions & 2 deletions src/error/mod.rs
Expand Up @@ -19,8 +19,11 @@ use crate::{
App, AppSettings,
};

mod context;
mod kind;

pub use context::ContextKind;
pub use context::ContextValue;
pub use kind::ErrorKind;

/// Short hand for [`Result`] type
Expand All @@ -45,9 +48,8 @@ pub struct Error {

#[derive(Debug)]
struct ErrorInner {
/// The type of error
kind: ErrorKind,
/// Formatted error message, enhancing the cause message with extra information
context: Vec<(ContextKind, ContextValue)>,
message: Message,
source: Option<Box<dyn error::Error + Send + Sync>>,
wait_on_exit: bool,
Expand Down Expand Up @@ -82,6 +84,11 @@ impl Error {
self.inner.kind
}

/// Additional information to further qualify the error
pub fn context(&self) -> impl Iterator<Item = (ContextKind, &ContextValue)> {
self.inner.context.iter().map(|(k, v)| (*k, v))
}

/// Should the message be written to `stdout` or not?
#[inline]
pub fn use_stderr(&self) -> bool {
Expand Down Expand Up @@ -147,6 +154,7 @@ impl Error {
Self {
inner: Box::new(ErrorInner {
kind,
context: Vec::new(),
message: message.into(),
source: None,
wait_on_exit,
Expand Down

0 comments on commit cce2c68

Please sign in to comment.