When writing code that uses Result
type, you may want different behavior for users and developers.
Result
.Err
value is created.If you make a unique error it's not hard to search for it, but if the error is from the standard library, the error may be very generic.
For example, it's impossible to know which read
command caused an unexpected end-of-file without manually changing every file.read()?
to file.read().unwrap()
.
Is there a convenient way to get a stack-trace from a Result
?
A weak but workable solution could be to make a macro for reading, read_in_release_unwrap_in_debug!(file, data)
... but this feels very awkward.
I have a file reader with many read
calls and one fails. I'm not sure which. At run-time, I want to push the result back to the caller. For debugging, I want the failed read call to stop or somehow let me know its line number.
Stack trace error is a generic term frequently associated with long error messages. The stack trace information identifies where in the program the error occurs and is helpful to programmers. For users, the long stack track information may not be very useful for troubleshooting web errors.
"Using or expressed in more words than are needed"
A result by itself doesn't have any backtrace information, but you can add it to custom error types.
The error_chain crate is an example which generates an error type for you, for which you get backtrace generation for free when the RUST_BACKTRACE
environment variable is set.
You could also use the backtrace library directly and do it yourself.
If you use anyhow
you can get this for free! The catch is you need to use nightly and enable an environment variable:
RUST_BACKTRACE=1 cargo +nightly run
This is the tracking issue for stabilisation, and a PR to stabilise it. Looks like there is some disagreement about whether it needs to work in no_std before being stabilised or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With