0

If I have a file like this:

use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {   

   Err("May
June")?

}

I get this result:

Error: "May\nJune"

Is it possible to get the unquoted string on output? Like this:

Error: May
June

I tried this:

Err("May
June").map_err(|e|
   format!("{:?}", e)
)?

but it just made it worse:

Error: "\"May\\nJune\""

2 Answers 2

5

You have to print the error yourself instead of relying on the default fallback implementation.

main() -> Result<…> prints Debug version of the error (where strings are escaped). It's intended as a quick'n'dirty solution for examples or playpens, and not for real programs where anyone would care about presentation of the output.

Use:

fn main() {
   if let Err(e) = run() {
       eprintln!("{}", e);
       std::process::exit(1);
   }
}

fn run() -> Result<(), Box<dyn Error>> {
   // etc
}

It will print the error using Display formatting.

There's nothing special about main()'s built-in error handling, so you're not losing anything by printing the error yourself.

There's also an alternative solution of implementing a custom Debug implementation on errors to make the Debug implementation print a non-debug one, but IMHO that's a hack, and needs more code than just doing the straightforward print. If you want that hack, have a look at the anyhow crate.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was originally doing pretty much this, but then I thought why print and exit, when I could just return an error. Full circle.
0

It might be overkill to pull in an extra dependency for this, but you can use the terminator crate, which offers a new error type intended to be returned from main that delegates to the Display implementation when printed with Debug. Then your example would look like this...

use terminator::Terminator;

fn main() -> Result<(), Terminator> {   
   Err("May
June")?
}

...and the output would be this:

Error: May
June

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.