Currently, I'm working on a project where I use several crates that return different errors. I'm trying to not use unwrap on a result but instead passing the error upwards using the question mark syntax. To be able to do this I created my own error enum that has variants for the different types of errors from the different crates I'm using and then use map_err to map the errors to my error enum. I also decided that I should add the line and file where I remapped the error so I could see where I encountered the error.
My error enum#[derive(Debug, Clone)]
pub enum Error {
GameError(ggez::GameError, String),
RonError(ron::error::Error, String),
}
Example of mapping an error
let rdr = filesystem::open(ctx, gen_conf_path)
.map_err(|e| {
Error::GameError(e, format!("at line {} in {}", line!(), file!()))
})?;
The problem with that is that the closure I need to send to map_err
becomes quite long and is essentially the same every time except for the enum variant I'm mapping to. So I want to create a macro that generates the closure for the correct enum variant. So i could write something like the following.
let rdr = filesystem::open(ctx, gen_conf_path).map_err(map_to!(Error::GameError))?
And the map_to!
macro would generate the code i had before.
Is this possible? Can I send an enum variant to a macro and let it construct it or should I do this in a completely different way?