Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pass source error to with_context closure? #29

Closed
miquels opened this issue Oct 20, 2019 · 2 comments
Closed

pass source error to with_context closure? #29

miquels opened this issue Oct 20, 2019 · 2 comments

Comments

@miquels
Copy link

miquels commented Oct 20, 2019

I like to log the Display version of an error instead of the Debug version, because it's then all on one line which I like better for logfiles. However there is currently no way to log the original error. I would like to be able to do:

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

It's probably too late to change with_context to take an argument - besides, it would not make sense for Options. Maybe error_context? POC here: https://github.com/miquels/anyhow/commit/4a79660fa0588c097b9ae3d143bb7e54b928b97b

@dtolnay
Copy link
Owner

dtolnay commented Oct 20, 2019

I would recommend not putting the cause's message into the outer error's message. Instead you can print the causes in whatever formatting you want, such as separated by ::

print!("{}", error);
error.chain().skip(1).for_each(|e| print!(": {}", e));

If you want the cause to appear in the outer error's message anyway, you would use map_err:

let content = fs::read(&path)
    .map_err(|e| {
        let context = format!("failed to read instrs from {}: {}", path.display(), e);
        Error::new(e).context(context)
    })?;

@miquels
Copy link
Author

miquels commented Oct 20, 2019

Okay, thanks. I'll probably write some macros to do it that way, then.

@miquels miquels closed this as completed Oct 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants