Skip to content

Commit add338d

Browse files
committed
feat: improve error printing
When using `Result::expect()`, (e.g. in the default `cot::main`) errors are printed using `Debug` printer. This causes very ugly errors to be produced. Instead, when the alternate mode is not being used, just format the error nicely, along with the error source chain. This roughly duplicates the `anyhow::Error` error printing logic: https://docs.rs/anyhow/latest/anyhow/struct.Error.html#method.chain
1 parent 460b273 commit add338d

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

cot-core/src/error/error_impl.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,26 @@ impl Error {
171171

172172
impl Debug for Error {
173173
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174-
Debug::fmt(&self.repr, f)
174+
// If the alternate (`{:#?}`) formatting has been specified, print out the
175+
// `Debug` formatting normally. If not, (which is the case when using
176+
// `Result::unwrap()` or `Result::expect()`) pretty print the error.
177+
if f.alternate() {
178+
Debug::fmt(&self.repr, f)
179+
} else {
180+
Display::fmt(&self.repr.inner, f)?;
181+
182+
writeln!(f)?;
183+
writeln!(f)?;
184+
writeln!(f, "caused by:")?;
185+
let mut source = self.source();
186+
while let Some(e) = source {
187+
writeln!(f, " {e}")?;
188+
189+
source = e.source();
190+
}
191+
192+
Ok(())
193+
}
175194
}
176195
}
177196

0 commit comments

Comments
 (0)