From 1c46f19592d041919f18736cb45ec6046d7d3b00 Mon Sep 17 00:00:00 2001 From: Derick Eddington Date: Thu, 18 Jul 2024 17:30:36 -0700 Subject: [PATCH] node: Fix `main` to print early errors 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 --- radicle-node/src/main.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/radicle-node/src/main.rs b/radicle-node/src/main.rs index ca7b93a1..f62a9988 100644 --- a/radicle-node/src/main.rs +++ b/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); }