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?
unwrap
is not supposed to display pretty error messages. Whenunwrap
panics, something is supposed to have gone horribly wrong. If you want to print out theString
inside anErr
you can print it tostderr
witheprintln!
and then handle the error properly after that: