How to find where error happen

when i use anyhow and thiserror, It's easy to use ? to get the right value and retrun error,but when error accutally happened,It's difficult to locate the root cause.Is there any easy way to do that.I found that is a little bit uncomfortable to use backtrace feature and root_cause() function,because it also cannot tell me which line the error occures.

If you’re using anyhow, then you should be using its context() and with_context() to attach context to errors. The code example on that page demonstrates how to use them together with ?:

pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
    it.detach().context("Failed to detach the important thing")?;

    let path = &it.path;
    let content = fs::read(path)
        .with_context(|| format!("Failed to read instrs from {}", path.display()))?;

    Ok(content)
}

thx,but I want a way to show which line the error occurs. It's boring to write line!() inside error message, Is there any conveniently way?

If you use separate context messages for every error site, you'll be able to infer the line from the message. Is this not enough for some reason?

If you really need line numbers, that’s often a sign that the error is a bug in your program, not a proper error. In that case, you should usually not return it with Result but panic instead.

3 Likes

I'm wondering why you want to know the line number when an error occurs.

The majority of errors are significant features of your program and should be held in the same high regard as the non-error code. What you want o know is what the error is and what to do about it. For example:

  1. A user provides invalid input. That is a common and expected occurrence that you will most likely want to handle. By re prompting for example.

  2. A socket connection fails. Also a common and expected occurrence you will likely want to handle. By trying to reconnect for example.

And so on. If you squint at it these are not errors. They are just part of the normal day to day running of the program. I don't see how knowing the line number is useful here.

If what I say above is not true for the event that has happened, then it is unexpected (dare I say an exception). Likely it is catastrophic, like a disk failure, stack overflow, out of memory or a bug in your code. In that case a panic is called for with the resulting stack trace.

1 Like