Home > Software engineering >  Rust: Make unwrap() print error.display() instead of error.debug()
Rust: Make unwrap() print error.display() instead of error.debug()

Time:11-17

In a Rust program, I am using a Result which uses a String as its Error type:

fn foo() -> Result<String, String>

The String I return as an error looks something like this:
lorem\nipsum

Now I call my function and unwrap it as such:
foo.unwrap();

Now when foo() returns an Error, it prints the error as follows:
lorem\nipsum

However, what I actually would want to see is the following error message:

lorem
ipsum

As far as I can tell, the reason for this behaviour is that unwrap(), calls debug() instead of display() which in the case of the String, is implemented differently (a new line is displayed as a new line, but debug-printed as "\n").

Is there a quick way how I could unwrap() my result in a way that it calls display() instead of debug() for the printed error to actually show newlines instead of "\n"s?

CodePudding user response:

unwrap is not supposed to display pretty error messages. When unwrap panics, something is supposed to have gone horribly wrong. If you want to print out the String inside an Err you can print it to stderr with eprintln! and then handle the error properly after that:

if let Err(e) = foo() {
    eprintln!("{}", e);
    // handle the error properly here
}
  • Related