Errors not Formatting \n

I am returning errors like this:

return Err(From::from(format!(
		"functionname: the stamp {} is the same as the last one, quitting!\n", dats.stamp)));

Why does the panic message include literal \n, rather than throwing a new line after itself, as I would expect when using format! ?

Panic message is printed with fmt::Debug formatter, and impl fmt::Debug for str prints with Debug escaping which tries to print it like a string literal.

Thanks. Hmm, is that supposed to be helpful? I have some doubts about that.
I output these errors to a log file and it really messes it up.

Note that debug print format is explicitly not stable, it may change in the future without warning. Any code that tries to parse it may subject to break in long-term scenario.

Well, good, then maybe they will change it to sensibly interpreting \n

If you're outputting them to a log file, can you not use the display formatting when writing them?

I am redirecting the std output(s) to the log file.
How can I use the display formatting instead? Any hints?

You can use set_hook to override those behaviour with whatever behaviour you want.

Use ? instead of unwrap and catch the error at the top level with a match that prints the error using display.

1 Like

Unfortunately set_hook won't help you. The error has already been converted into a string when it gets to the hook. It is converted here.

3 Likes

Yes it has been converted to a string, but set_hook disables the default of debug printing that string and allows you to display print it instead (or error! it into your logging library).

EDIT: oh, you mean the unwrap has debug printed the error already... that is a problem. I guess the other local workaround would be to wrap the string in a newtype that forwards debug to display when creating the error.

1 Like

Well, somehow I did not think it was going to be simple :smiley:

The idiomatic solution would be to return the error to somewhere that can handle it, and have the main function handle top-level errors by printing them in the way you want them printed.

That said, you could cheat by wrapping your error in one of these, which explicitly uses the Display implementation inside the Debug impl block.

2 Likes

Mostly I want to quit on errors anyway. So as far as I am concerned, all this error handling is more bother than what it is worth. I wish there was a way to turn it all off altogether.

I have yet to see any error recovery where it is actually meaningful and not misleading to continue with some different tack of computation afterwards (the stated reason for all this baggage).

So, my simple solution, good enough for the vast majority of my needs is:

eprintln!("function-name: my own error message {} {}",var1,var2,...);
panic!();

The output of this actually looks neat, unlike the rusty errors. Also, panic!(); returns the line-number, which together with my own proper error message is all the information I need.