Skip to content

Commit

Permalink
enh(errors): improve logs of errors to easier debug on prod
Browse files Browse the repository at this point in the history
  • Loading branch information
eythaann committed Oct 9, 2024
1 parent 3a1e438 commit ec758ea
Show file tree
Hide file tree
Showing 13 changed files with 276 additions and 274 deletions.
60 changes: 4 additions & 56 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ path = "src/background/main.rs"
incremental = true
rustflags = ["-Z", "threads=8"]

[profile.release]
debug = 1
opt-level = "z"
lto = true
codegen-units = 1
rustflags = ["-Z", "threads=8"]

[build-dependencies]
tauri-build = { version = "2.0.0-rc", features = [] }

Expand All @@ -42,7 +49,6 @@ tauri-plugin-http = "2.0.0-rc"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_yaml = "0.9.34"
color-eyre = "0.6.2"
lazy_static = "1.4.0"
parking_lot = "0.12.1"
log = "0.4"
Expand All @@ -68,6 +74,8 @@ notify-debouncer-full = "0.3.1"
encoding_rs = "0.8.34"
evalexpr = "=11.3.0"
quick-xml = { version = "0.36.2", features = ["serialize", "encoding"] }
backtrace = "0.3.71"
owo-colors = "4.1.0"

[dependencies.windows]
version = "=0.58.0"
Expand Down
121 changes: 72 additions & 49 deletions src/background/error_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,38 @@ macro_rules! define_app_errors {
($(
$variant:ident($error_type:ty);
)*) => {
#[derive(Debug)]
pub enum AppError {
$(
$variant($error_type),
)*
}

$(
impl From<$error_type> for AppError {
fn from(err: $error_type) -> Self {
AppError::$variant(err)
let backtrace = backtrace::Backtrace::new();
AppError { msg: format!("{}({:?})", stringify!($variant), err), backtrace }
}
}
)*
};
}

#[macro_export]
macro_rules! log_error {
($($result:expr),*) => {
$(
if let Err(err) = $result {
log::error!("{:?}", err);
}
)*
};
}

pub struct AppError {
msg: String,
backtrace: backtrace::Backtrace,
}

define_app_errors!(
Seelen(String);
Custom(String);
Io(std::io::Error);
Tauri(tauri::Error);
TauriShell(tauri_plugin_shell::Error);
Eyre(color_eyre::eyre::Error);
Windows(windows::core::Error);
SerdeJson(serde_json::Error);
SerdeYaml(serde_yaml::Error);
Expand All @@ -44,9 +53,52 @@ define_app_errors!(
EvalExpr(evalexpr::EvalexprError);
);

impl From<&str> for AppError {
fn from(err: &str) -> Self {
AppError::Seelen(err.to_owned())
impl std::fmt::Debug for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)?;

let frames = self.backtrace.frames();
if !frames.is_empty() {
writeln!(f)?;
}

let mut index = 0;
for frame in frames {
for symbol in frame.symbols() {
let name = match symbol.name() {
Some(name) => name.to_string(),
None => continue,
};

// skip backtrace traces
if name.starts_with("backtrace") {
continue;
}

// 2) skip trace of other modules/libraries specially tracing of tao and tauri libs
if !name.starts_with("seelen_ui") {
index += 1;
continue;
}

writeln!(f, " {}: {}", index, name)?;
if let Some(file) = symbol.filename() {
write!(f, " at: \"{}", file.to_string_lossy())?;
if let Some(line) = symbol.lineno() {
write!(f, ":{}", line)?;
if let Some(col) = symbol.colno() {
write!(f, ":{}", col)?;
}
}
writeln!(f, "\"")?;
} else {
writeln!(f, " at: <unknown>")?
}

index += 1;
}
}
Ok(())
}
}

Expand All @@ -56,19 +108,19 @@ impl std::fmt::Display for AppError {
}
}

impl From<&str> for AppError {
fn from(err: &str) -> Self {
err.to_owned().into()
}
}

// needed to tauri::command macro (exposed functions to frontend)
impl From<AppError> for tauri::ipc::InvokeError {
fn from(val: AppError) -> Self {
tauri::ipc::InvokeError::from(val.to_string())
}
}

impl From<AppError> for String {
fn from(err: AppError) -> String {
format!("{}", err)
}
}

impl From<tauri_plugin_shell::process::Output> for AppError {
fn from(output: tauri_plugin_shell::process::Output) -> Self {
if !output.stderr.is_empty() {
Expand All @@ -81,33 +133,4 @@ impl From<tauri_plugin_shell::process::Output> for AppError {
}
}

impl std::error::Error for AppError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
AppError::Eyre(err) => Some(err.root_cause()),
AppError::Io(err) => Some(err),
AppError::Tauri(err) => Some(err),
AppError::Windows(err) => Some(err),
AppError::SerdeJson(err) => Some(err),
AppError::Utf8(err) => Some(err),
AppError::Utf16(err) => Some(err),
AppError::CrossbeamRecv(err) => Some(err),
AppError::TauriShell(err) => Some(err),
AppError::TryFromInt(err) => Some(err),
_ => None,
}
}
}

pub type Result<T = (), E = AppError> = core::result::Result<T, E>;

#[macro_export]
macro_rules! log_error {
($($result:expr),*) => {
$(
if let Err(err) = $result {
log::error!("{:?}", err);
}
)*
};
}
pub type Result<T = ()> = core::result::Result<T, AppError>;
14 changes: 12 additions & 2 deletions src/background/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use std::{
time::{Duration, Instant},
};

use color_eyre::owo_colors::OwoColorize;
use itertools::Itertools;
use lazy_static::lazy_static;
use parking_lot::Mutex;
Expand Down Expand Up @@ -114,10 +113,21 @@ impl HookManager {
if !LOG_WIN_EVENTS.load(Ordering::Relaxed) || event == WinEvent::ObjectLocationChange {
return;
}
let event_value = {
#[cfg(dev)]
{
use owo_colors::OwoColorize;
event.green()
}
#[cfg(not(dev))]
{
&event
}
};

log::debug!(
"{:?}({:?}) || {} || {} || {}",
event.green(),
event_value,
origin.0,
WindowsApi::exe(origin).unwrap_or_default(),
WindowsApi::get_class(origin).unwrap_or_default(),
Expand Down
3 changes: 1 addition & 2 deletions src/background/instance.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use color_eyre::eyre::eyre;
use getset::{Getters, MutGetters};

use crate::{
Expand Down Expand Up @@ -29,7 +28,7 @@ unsafe impl Send for SeelenInstanceContainer {}
impl SeelenInstanceContainer {
pub fn new(hmonitor: HMONITOR, settings: &FullState) -> Result<Self> {
if hmonitor.is_invalid() {
return Err(eyre!("Invalid Monitor").into());
return Err("Invalid Monitor".into());
}
let mut instance = Self {
handle: hmonitor,
Expand Down
13 changes: 6 additions & 7 deletions src/background/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ mod winevent;

use std::io::{BufWriter, Write};

use color_eyre::owo_colors::OwoColorize;
use error_handler::Result;
use exposed::register_invoke_handler;
use itertools::Itertools;
Expand All @@ -44,8 +43,8 @@ use utils::PERFORMANCE_HELPER;
use windows::Win32::Security::{SE_DEBUG_NAME, SE_SHUTDOWN_NAME};
use windows_api::WindowsApi;

fn register_panic_hook() {
std::panic::set_hook(Box::new(|info| {
fn register_panic_hook() -> Result<()> {
std::panic::set_hook(Box::new(move |info| {
let cause = info
.payload()
.downcast_ref::<String>()
Expand All @@ -69,10 +68,11 @@ fn register_panic_hook() {

log::error!(
"A panic occurred:\n Cause: {}\n Location: {}",
cause.cyan(),
string_location.purple()
cause,
string_location
);
}));
Ok(())
}

fn print_initial_information() {
Expand Down Expand Up @@ -162,8 +162,7 @@ fn is_already_runnning() -> bool {
}

fn main() -> Result<()> {
register_panic_hook();
color_eyre::install()?;
register_panic_hook()?;
trace_lock!(PERFORMANCE_HELPER).start("setup");

let command = trace_lock!(SEELEN_COMMAND_LINE).clone();
Expand Down
Loading

0 comments on commit ec758ea

Please sign in to comment.