Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract an iterator that cleans redundant nested error text #383

Merged
merged 1 commit into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ mod error_chain;
pub use crate::error_chain::*;

mod report;
#[cfg(feature = "std")]
pub use report::CleanedErrorText;
pub use report::{Report, __InternalExtractErrorType};

doc_comment::doc_comment! {
Expand Down
122 changes: 100 additions & 22 deletions src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,33 +272,23 @@ impl<'a> ReportFormatter<'a> {
fn cleaned_error_trace(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
const NOTE: char = '*';

let mut original_messages = ChainCompat::new(self.0).map(ToString::to_string);
let mut prev = original_messages.next();

let mut cleaned_messages = vec![];
let mut any_cleaned = false;
let mut any_removed = false;
for msg in original_messages {
if let Some(mut prev) = prev {
let cleaned = prev.trim_end_matches(&msg).trim_end().trim_end_matches(':');
if cleaned.is_empty() {
let cleaned_messages: Vec<_> = CleanedErrorText::new(self.0)
.flat_map(|(_, mut msg, cleaned)| {
if msg.is_empty() {
any_removed = true;
// Do not add this to the output list
} else if cleaned != prev {
any_cleaned = true;
let cleaned_len = cleaned.len();
prev.truncate(cleaned_len);
prev.push(' ');
prev.push(NOTE);
cleaned_messages.push(prev);
None
} else {
cleaned_messages.push(prev);
if cleaned {
any_cleaned = true;
msg.push(' ');
msg.push(NOTE);
}
Some(msg)
}
}

prev = Some(msg);
}
cleaned_messages.extend(prev);
})
.collect();

let mut visible_messages = cleaned_messages.iter();

Expand Down Expand Up @@ -357,6 +347,94 @@ fn trace_cleaning_enabled() -> bool {
!DISABLED.get(|| env::var_os(SNAFU_RAW_ERROR_MESSAGES).map_or(false, |v| v == "1"))
}

/// An iterator over an Error and its sources that removes duplicated
/// text from the error display strings.
///
/// It's common for errors with a `source` to have a `Display`
/// implementation that includes their source text as well:
///
/// ```text
/// Outer error text: Middle error text: Inner error text
/// ```
///
/// This works for smaller errors without much detail, but can be
/// annoying when trying to format the error in a more structured way,
/// such as line-by-line:
///
/// ```text
/// 1. Outer error text: Middle error text: Inner error text
/// 2. Middle error text: Inner error text
/// 3. Inner error text
/// ```
///
/// This iterator compares each pair of errors in the source chain,
/// removing the source error's text from the containing error's text:
///
/// ```text
/// 1. Outer error text
/// 2. Middle error text
/// 3. Inner error text
/// ```
#[cfg(feature = "std")]
pub struct CleanedErrorText<'a>(Option<CleanedErrorTextStep<'a>>);

#[cfg(feature = "std")]
impl<'a> CleanedErrorText<'a> {
/// Constructs the iterator.
pub fn new(error: &'a dyn crate::Error) -> Self {
Self(Some(CleanedErrorTextStep::new(error)))
}
}

#[cfg(feature = "std")]
impl<'a> Iterator for CleanedErrorText<'a> {
/// The original error, the display string and if it has been cleaned
type Item = (&'a dyn crate::Error, String, bool);

fn next(&mut self) -> Option<Self::Item> {
use std::mem;

let mut step = self.0.take()?;
let mut error_text = mem::replace(&mut step.error_text, Default::default());

match step.error.source() {
Some(next_error) => {
let next_error_text = next_error.to_string();

let cleaned_text = error_text
.trim_end_matches(&next_error_text)
.trim_end()
.trim_end_matches(':');
let cleaned = cleaned_text.len() != error_text.len();
let cleaned_len = cleaned_text.len();
error_text.truncate(cleaned_len);

self.0 = Some(CleanedErrorTextStep {
error: next_error,
error_text: next_error_text,
});

Some((step.error, error_text, cleaned))
}
None => Some((step.error, error_text, false)),
}
}
}

#[cfg(feature = "std")]
struct CleanedErrorTextStep<'a> {
error: &'a dyn crate::Error,
error_text: String,
}

#[cfg(feature = "std")]
impl<'a> CleanedErrorTextStep<'a> {
fn new(error: &'a dyn crate::Error) -> Self {
let error_text = error.to_string();
Self { error, error_text }
}
}

#[doc(hidden)]
pub trait __InternalExtractErrorType {
type Err;
Expand Down
58 changes: 57 additions & 1 deletion tests/report.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use snafu::{prelude::*, IntoError, Report};
use snafu::{prelude::*, CleanedErrorText, IntoError, Report};

macro_rules! assert_contains {
(needle: $needle:expr, haystack: $haystack:expr) => {
Expand Down Expand Up @@ -162,3 +162,59 @@ struct TestFunctionError;
fn procedural_macro_works_with_test_functions() -> Result<(), TestFunctionError> {
Ok(())
}

#[track_caller]
fn assert_cleaning_step(iter: &mut CleanedErrorText, text: &str, removed_text: &str) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have test coverage for the case where a message contains :, but the subsequent part of the string represents an unreachable cause not exposed via source? No clean-up should happen in these cases.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean something like a leaf message saying “bad thing happened: restart your server”?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, or the case where the second part is indeed part of a sub-cause error message but the corresponding cause is deliberately not part of the error source chain.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I follow that second case. Do you mean something like this pseudocode?

#[snafu(display("Outer is better than Inner"))] // doesn't use `{source}` but just happens to end with the exact same text
struct Outer { source: Inner }

#[snafu(display("Inner"))]
struct Inner;

If so, I don't think there's any way to avoid that.

Copy link
Collaborator

@Enet4 Enet4 Jul 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about the code below. I suspect the confusion is because one is unlikely to do this in snafu, but if for any reason we have a source error which we do not want to expose as an error, the error text cleaning routine should not clean the message.

#[derive(Debug, Snafu)]
#[snafu(display("Epic fail: {}", hidden_source))]
struct Outer {
   hidden_source: Inner,
}

#[derive(Debug, Snafu)]
#[snafu(display("I AM ERROR"))]
struct Inner;

The display message of an Outer should be "Epic fail: I AM ERROR", per the recommendations of the error handling WG.


The situation you just mentioned is a curious one, though! Could we have problems with the outer error's message ending with the exact message as its source-error message?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we do not want to expose as an error

In that case, it would not be cleaned — by construction. This walks the Error::source chain to find the duplicate text. It'e effectively trying to retroactively apply the error handling WG's suggestion of (Error::source XOR "include it in Display) for errors that do both.

Calling Error::source on Outer will return None, so we will never get the Display string from Inner, so we will not use it to clean Outer's text.


Could we have problems with the outer error's message ending with the exact message as its source-error message?

It's always possible. That's why snafu::Report offers a way to disable the cleaning. I do think that it is pretty unlikely, however.

let (error, actual_text, actual_cleaned) =
iter.next().expect("Iterator unexpectedly exhausted");
let actual_original_text = error.to_string();

let original_text = [text, removed_text].concat();
let cleaned = !removed_text.is_empty();

assert_eq!(original_text, actual_original_text);
assert_eq!(text, actual_text);
assert_eq!(cleaned, actual_cleaned);
}

#[test]
fn cleaning_a_leaf_error_changes_nothing() {
#[derive(Debug, Snafu)]
#[snafu(display("But I am only C"))]
struct C;

let c = C;
let mut iter = CleanedErrorText::new(&c);

assert_cleaning_step(&mut iter, "But I am only C", "");
assert!(iter.next().is_none());
}

#[test]
fn cleaning_nested_errors_removes_duplication() {
#[derive(Debug, Snafu)]
#[snafu(display("This is A: {source}"))]
struct A {
source: B,
}

#[derive(Debug, Snafu)]
#[snafu(display("And this is B: {source}"))]
struct B {
source: C,
}

#[derive(Debug, Snafu)]
#[snafu(display("But I am only C"))]
struct C;

let a = A {
source: B { source: C },
};
let mut iter = CleanedErrorText::new(&a);

assert_cleaning_step(&mut iter, "This is A", ": And this is B: But I am only C");
assert_cleaning_step(&mut iter, "And this is B", ": But I am only C");
assert_cleaning_step(&mut iter, "But I am only C", "");
assert!(iter.next().is_none());
}