Search code examples
rusterror-handlingrust-result

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?


Solution

  • 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.