Skip to content

Instantly share code, notes, and snippets.

@StarterX4
Last active February 27, 2025 21:48
Show Gist options
  • Save StarterX4/6408f521fa51098ba24c45294f1da1dd to your computer and use it in GitHub Desktop.
Save StarterX4/6408f521fa51098ba24c45294f1da1dd to your computer and use it in GitHub Desktop.
Rust: simple and quiet Error result — when eprintln is enough. No painful error handling.
// SPDX-License-Identifier: MIT
use std::fmt;
use clap::Parser; //just for argument parsing
use colored::Colorize; //colored output
#[derive(Debug)]
pub struct QuietErr(Option<String>);
impl fmt::Display for QuietErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ref msg) = self.0 {
write!(f, "{}", msg)
} else {
write!(f, "")
}
}
}
impl std::error::Error for QuietErr {}
// Clap args
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[arg(short, long, value_name = "NAME")]
name: Option<String>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
if let Some(name) = args.name {
name_test(&name)?;
} else {
let err = format!("No name provided!");
eprintln!("{} {}", "Error:".red(), err);
return Err(Box::new(QuietErr(Some(err)))); //with return for e.g. GUI programs
}
}
fn name_test(name: &str) -> Result<(), Box<dyn std::error::Error>> {
if !name.is_empty() {
eprintln!("Heyo {}! {}", name.bold(), "It Works!".red());
return Err(Box::new(QuietErr(None))); //Quiet
}
Ok(());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment