Skip to content

Commit f94a40c

Browse files
authored
Make wasmtime_internal_error's error formatting more-compatible with anyhow's (#12306)
For the "caused by" error chain, anyhow doesn't use tabs and only prints a number when there are multiple causes.
1 parent 8cccb54 commit f94a40c

File tree

3 files changed

+43
-9
lines changed

3 files changed

+43
-9
lines changed

crates/error/src/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ mod sealed {
7373
/// failed to convert `999` into a `u8` (max = `255`)
7474
///
7575
/// Caused by:
76-
/// 0: out of range integral type conversion attempted
76+
/// out of range integral type conversion attempted
7777
/// "#.trim(),
7878
/// );
7979
/// ```

crates/error/src/error.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,8 +446,14 @@ impl fmt::Debug for Error {
446446

447447
if let Some(source) = inner.source() {
448448
f.write_str("\n\nCaused by:\n")?;
449+
let multiple_causes = source.source().is_some();
449450
for (i, e) in Chain::new(source).enumerate() {
450-
writeln!(f, "\t{i}: {e}")?;
451+
if multiple_causes {
452+
write!(f, "{i: >5}: ")?;
453+
} else {
454+
write!(f, " ")?;
455+
}
456+
writeln!(f, "{e}")?;
451457
}
452458
}
453459

@@ -717,8 +723,8 @@ impl Error {
717723
/// cannot frob the blobbins
718724
///
719725
/// Caused by:
720-
/// 0: failed to bonkinate
721-
/// 1: root cause
726+
/// 0: failed to bonkinate
727+
/// 1: root cause
722728
/// "#.trim(),
723729
/// ),
724730
/// );

crates/error/tests/tests.rs

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -640,11 +640,39 @@ fn fmt_debug() {
640640
let error = Error::msg("whoops").context("uh oh").context("yikes");
641641
let actual = format!("{error:?}");
642642

643-
let expected = "yikes\n\
644-
\n\
645-
Caused by:\n\
646-
\t0: uh oh\n\
647-
\t1: whoops\n";
643+
let expected = "\
644+
yikes
645+
646+
Caused by:
647+
0: uh oh
648+
1: whoops
649+
";
650+
651+
#[cfg(feature = "backtrace")]
652+
{
653+
assert!(actual.starts_with(expected));
654+
if let BacktraceStatus::Captured = error.backtrace().status() {
655+
assert!(actual.contains("Stack backtrace:"));
656+
}
657+
}
658+
659+
#[cfg(not(feature = "backtrace"))]
660+
{
661+
assert_eq!(actual, expected);
662+
}
663+
}
664+
#[test]
665+
fn fmt_debug_with_single_cause() {
666+
let error = Error::msg("whoops").context("uh oh");
667+
let actual = format!("{error:?}");
668+
669+
// NB: the causes are only numbered when there are multiple of them.
670+
let expected = "\
671+
uh oh
672+
673+
Caused by:
674+
whoops
675+
";
648676

649677
#[cfg(feature = "backtrace")]
650678
{

0 commit comments

Comments
 (0)