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?
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
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.)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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With