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

Implement WrapError for Option #408

Open
jalil-salame opened this issue Nov 15, 2024 · 1 comment · May be fixed by #409
Open

Implement WrapError for Option #408

jalil-salame opened this issue Nov 15, 2024 · 1 comment · May be fixed by #409

Comments

@jalil-salame
Copy link

anyhow implements it's Context trait on options. This helps avoid some boilerplate:

use anyhow::Context;

let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
let _ = map.get("d").with_context(|| format!("Key 'd' was missing from map: {map:?}"))?;

Currently the best way to do this with miette is by using a let else then bail!:

use miette::bail;

let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
let Some(_) = map.get("d") else {
    bail!("Key 'd' was missing from map: {map:?}"));
};

I'm willing to implement this if desired

@zkat
Copy link
Owner

zkat commented Nov 15, 2024

sounds good to me! go for it!

jalil-salame added a commit to jalil-salame/miette that referenced this issue Nov 16, 2024
Implement `WrapError` for `Option<T>`. This is inline with `anyhow` that
also implements `Context` for `Option<T>`.

The implementation requires us to introduce a `DisplayError` internal
only type, that creates an error from a type that only implements
`Display` (`Report::from_adhoc` requires the type to also implement
`Debug`, but `WrapError` only requires it to implement `Display`).

For this I copied `MessageError` and adapted it to implement `Debug`
using the underlying type's `Display` impl. This is a bit of a hack, but
anyhow does [something similar][1].

Closes zkat#408

[1]: https://docs.rs/anyhow/latest/src/anyhow/wrapper.rs.html#34
@jalil-salame jalil-salame linked a pull request Nov 16, 2024 that will close this issue
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

Successfully merging a pull request may close this issue.

2 participants