Reputation: 1
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\""
Upvotes: 0
Views: 177
Reputation: 5949
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
Upvotes: 0
Reputation: 100120
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.
Upvotes: 5