From 989debe8d7438028245b965b9d464032a0d3e0a3 Mon Sep 17 00:00:00 2001 From: sigoden Date: Wed, 23 Oct 2024 17:23:40 +0800 Subject: refactor: improve error rendering (#948) --- src/utils/mod.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'src/utils/mod.rs') diff --git a/src/utils/mod.rs b/src/utils/mod.rs index a551855..27dac4a 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -145,16 +145,30 @@ pub fn fuzzy_match(text: &str, pattern: &str) -> bool { pub fn pretty_error(err: &anyhow::Error) -> String { let mut output = vec![]; output.push(format!("Error: {err}")); - for (i, cause) in err.chain().skip(1).enumerate() { - if i == 0 { - output.push("Caused by:".to_string()); + let causes: Vec<_> = err.chain().skip(1).collect(); + let causes_len = causes.len(); + if causes_len > 0 { + output.push("\nCaused by:".to_string()); + if causes_len == 1 { + output.push(format!(" {}", indent_text(causes[0], 4).trim())); + } else { + for (i, cause) in causes.into_iter().enumerate() { + output.push(format!("{i:5}: {}", indent_text(cause, 7).trim())); + } } - output.push(format!(" {i}: {cause}")); } - output.push(String::new()); output.join("\n") } +pub fn indent_text(s: T, size: usize) -> String { + let indent_str = " ".repeat(size); + s.to_string() + .split('\n') + .map(|line| format!("{}{}", indent_str, line)) + .collect::>() + .join("\n") +} + pub fn error_text(input: &str) -> String { color_text(input, nu_ansi_term::Color::Red) } -- cgit v1.2.3