Need to add backtrace field for thiserror custom error

I want to add backtrace field for my custom errors implemented with thiserror crate, but got an error on compile:

error[E0658]: use of unstable library feature 'error_generic_member_access'
  --> src/main.rs:14:10
   |
14 | #[derive(Error, Debug)]
   |          ^^^^^
   |
   = note: see issue #99301 <https://github.com/rust-lang/rust/issues/99301> for more information
   = note: this error originates in the derive macro `Error` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0599]: no method named `thiserror_provide` found for reference `&FromUtf8Error` in the current scope
  --> src/main.rs:18:9
   |
18 |         source: std::string::FromUtf8Error,
   |         ^^^^^^ method not found in `&FromUtf8Error`

This is my code:

use anyhow::{Context, Result as AnyResult};

use std::backtrace::Backtrace;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum StringError {
    #[error("utf8 error")]
    UTF8Error {
        source: std::string::FromUtf8Error,
        backtrace: Backtrace,
    },
}

fn first(str_bytes: Vec<u8>) -> AnyResult<String> {
    let str = second(str_bytes)?;
    Ok(str)
}

fn second(str_bytes: Vec<u8>) -> Result<String, StringError> {
    String::from_utf8(str_bytes)
        .map_err(|e| StringError::UTF8Error {
            source: e,
            backtrace: Backtrace::force_capture(),
        })
}

#[tokio::main]
async fn main() -> AnyResult<()> {
    let broken_str = vec![0, 159, 146, 150];
    let str = first(broken_str)?;
    Ok(())
}

This is sandbox to reproduce.

Could somebody explain what's wrong with my code and how to fix this ?

Here's your playground example modofied to run in Nightly:

1 Like

could you tell if it possible to allow backtrace for stable ?

It's not currently possible. Here's the tracking issue: Tracking Issue for `error_generic_member_access` · Issue #99301 · rust-lang/rust · GitHub

1 Like