Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trace the cause of an error result?

When writing code that uses Result type, you may want different behavior for users and developers.

  • When writing an application that gracefully handles errors, it's nice to use Result.
  • During development you may want to "catch" the error to see what line of code creates the error or get a stack-trace the moment the 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.

like image 572
ideasman42 Avatar asked Feb 16 '17 13:02

ideasman42


People also ask

What is stack trace error?

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.

What is a verbose error message?

"Using or expressed in more words than are needed"


2 Answers

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.

like image 195
Chris Emerson Avatar answered Sep 22 '22 16:09

Chris Emerson


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.

like image 22
Timmmm Avatar answered Sep 22 '22 16:09

Timmmm