Radish alpha
h
rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5
Radicle Heartwood Protocol & Stack
Radicle
Git
node: Fix `main` to print early errors
Merged did:key:z6Mko5mi...bgMH opened 1 year ago

Otherwise, previously, when an error occurred before logger::init() then no message about the error would be shown, because log ignores messages generated before the logger is initialized. E.g. when $RAD_HOME/config.json is missing, invoking radicle-node directly (i.e. not via rad node start) would fail without any explanation being logged nor printed. There also are some other possible errors that can occur before logger::init() where no message would’ve been shown.

The fix is to detect if the logger is enabled, which it won’t be when it hasn’t been initialized, and if not then fallback to printing directly to stderr.

To show the lower-level source of an error, like previously, and to avoid now needing more conditionals with more format strings for all possibilities of err.source().is_some() and log_enabled!(), the “alternate” form ({:#}) of formatting anyhow::Error is now used. This also introduces a change in behavior such that the entire chain of source errors will now be shown, instead of only the first in the chain, which seems more desirable for errors that cause fatal exiting of radicle-node. Note that this form still formats as only a single line, like previously.

The prefix “Error: “ is used for the new fallback printing, because in this case it’s not a log message (though, it might be written to the log file), and because that prefix is consistent with how Rust errors that cause immediate termination are usually printed directly. For the opposite case, the “Fatal: “ prefix serves to distinguish it as being fatal among the many other various log messages.

While it would be possible to instead return anyhow::Result<()> from main, to achieve the printing of early errors (and exiting with failure code), that would cause undesirable duplication, for non-early errors that occur after logger::init(), of the error message where it would be written to both the log file and to stderr which often is the same as the log file.

Signed-off-by: Derick Eddington kcired@pm.me

1 file changed +3 -3 a04381f4 1c46f195
modified radicle-node/src/main.rs
@@ -130,10 +130,10 @@ fn execute() -> anyhow::Result<()> {

fn main() {
    if let Err(err) = execute() {
-
        if let Some(src) = err.source() {
-
            log::error!(target: "node", "Fatal: {err}: {src}");
+
        if log::log_enabled!(target: "node", log::Level::Error) {
+
            log::error!(target: "node", "Fatal: {err:#}");
        } else {
-
            log::error!(target: "node", "Fatal: {err}");
+
            eprintln!("Error: {err:#}");
        }
        process::exit(1);
    }