Last active
October 13, 2020 18:41
-
-
Save zicklag/5cda6c2a1d1e93dd84dd962c2f05695b to your computer and use it in GitHub Desktop.
Starter main.rs and lib.rs files for Rust applications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use thiserror::Error; | |
use tracing as trc; | |
/// An error that indicates that the program should exit with the given code | |
#[derive(Error, Debug)] | |
#[error("Program exited {0}")] | |
struct Exit(i32); | |
fn run() { | |
// Install tracing for logs | |
install_tracing(); | |
// Install color error printing | |
color_eyre::install().expect("Could not install error handler"); | |
// Start the application and capture errors | |
match start() { | |
// Do nothing for happy runs! | |
Ok(()) => (), | |
// Hnadle errors | |
Err(report) => { | |
// If the error is an exit code | |
if let Some(e) = report.downcast_ref::<Exit>() { | |
let code = e.0; | |
// If the code is zero, exit cleanly | |
if code == 0 { | |
std::process::exit(0); | |
// If the code is non-zero print the error and then exit with that code | |
} else { | |
println!("{:?}", report); | |
std::process::exit(e.0); | |
} | |
// If the error is any other kind of error print it and exit 1 | |
} else { | |
println!("{:?}", report); | |
std::process::exit(1); | |
} | |
} | |
} | |
} | |
fn install_tracing() { | |
use tracing_error::ErrorLayer; | |
use tracing_subscriber::prelude::*; | |
use tracing_subscriber::{fmt, EnvFilter}; | |
// Build the tracing layers | |
let fmt_layer = fmt::layer().with_target(false); | |
let filter_layer = EnvFilter::try_from_default_env() | |
.or_else(|_| EnvFilter::try_new("info")) | |
.unwrap(); | |
// Add all of the layers to the subscriber and initialize it | |
tracing_subscriber::registry() | |
.with(filter_layer) | |
.with(fmt_layer) | |
.with(ErrorLayer::default()) | |
.init(); | |
} | |
/// Start your program | |
fn start() -> eyre::Result<()> { | |
trc::info!("Starting program"); | |
Ok(()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
my_crate::run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment