Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "Error:" output when returning Result from main?

I'm trying to make my own custom errors but I do not want Rust to automatically add Error: in front of the error messages.

use std::error::Error;
use std::fmt;

#[derive(Debug)]
enum CustomError {
    Test
}

fn main() -> Result<(), CustomError> {
    Err(CustomError::Test)?;
    Ok(())
}

Expected output (stderr):

Test

Actual output (stderr):

Error: Test

How do I avoid that?

like image 660
PotatoParser Avatar asked Aug 30 '25 15:08

PotatoParser


1 Answers

The Error: prefix is added by the Termination implementation for Result. Your easiest option to avoid it is to make main() return () instead, and then handle the errors yourself in main(). Example:

fn foo() -> Result<(), CustomError> {
    Err(CustomError::Test)?;
    Ok(())
}

fn main() {
    if let Err(e) = foo() {
        eprintln!("{:?}", e);
    }
}

If you are fine using unstable features, you can also

  • implement the Termination and Try traits on a custom result type, which would allow you to use your original code in main(), but customize its behaviour. (For this simple case, this seems overkill to me.)
  • return an ExitCode from main, which allows you to indicate ExitCode::SUCCESS or ExitCode::FAILURE. You can also set an exit code using std::process::exit(), but I'm not aware of a way of accessing the platform-dependent success and failure codes in stable Rust.
like image 94
Sven Marnach Avatar answered Sep 02 '25 13:09

Sven Marnach