summaryrefslogtreecommitdiffstats
path: root/lib/core/libimagerror/src/trace.rs
blob: e7bb5a3911395051e79fdafcf6b03ff50dfc85eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
esser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use std::process::exit; use anyhow::Error; use ansi_term::Colour::Red; pub fn trace_error(e: &Error) { eprintln!("{}: {}", Red.blink().paint("ERROR[ 0]"), e); let mut i = 0; e.chain().skip(1).for_each(|cause| { eprintln!("{prefix}: {error}", prefix = Red.blink().paint(format!("ERROR[{:>4}]", i + 1)), error = cause); i += 1; }); } pub fn trace_error_dbg(e: &Error) { debug!("{}: {}", Red.blink().paint("ERROR[ 0]"), e); let mut i = 0; e.chain().skip(1).for_each(|cause| { debug!("{prefix}: {error}", prefix = Red.blink().paint(format!("ERROR[{:>4}]", i + 1)), error = cause); i += 1; }); } /// Helper functions for `Result<T, E>` types to reduce overhead in the following situations: /// /// ```ignore /// function().map_err(|e| { trace_error(&e); e }) /// ``` /// /// and variants pub trait MapErrTrace { type Output; fn map_err_trace(self) -> Self; fn map_err_trace_exit_unwrap(self) -> Self::Output; } impl<U> MapErrTrace for Result<U, Error> { type Output = U; /// Simply call `trace_error()` on the Err (if there is one) and return the error. /// /// This does nothing besides the side effect of printing the error trace fn map_err_trace(self) -> Self { self.map_err(|e| { trace_error(&e); e }) } /// Trace the error and exit or unwrap the Ok(_). fn map_err_trace_exit_unwrap(self) -> Self::Output { self.map_err(|e| { trace_error(&e); exit(1) }).unwrap() } }