Skip to content

Allow unboxing source #505

@Kyuuhachi

Description

@Kyuuhachi

This program fails to downcast its source errors, since they are Box<MyError>, not MyError. As briefly mentioned on discord.

use snafu::ResultExt as _;

#[derive(Debug, snafu::Snafu)]
pub enum MyError {
	#[snafu(display("error: {error_code:08X}"))]
	LeafError { error_code: u32 },
	#[snafu(display("at depth {depth}"))]
	NodeError {
		depth: u32,
		#[snafu(source(from(MyError, Box::new)))]
		source: Box<MyError>
	},
}

fn main() {
	let e = fake_fn(3).unwrap_err();

	for e in std::iter::successors(Some(&e as &dyn std::error::Error), |e| e.source()) {
		if let Some(e) = e.downcast_ref::<MyError>() {
			println!("downcasted: {}", e);
		} else {
			println!("failed: {}", e);
		}
	}
}

fn fake_fn(depth: u32) -> Result<(), MyError> {
	if depth == 0 {
		LeafSnafu { error_code: 0xDEADBEEFu32 }.fail()
	} else {
		fake_fn(depth - 1).context(NodeSnafu { depth })
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions