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