The following test will not compile, since windows::Error does not implement the std::error::Error trait:
#[cfg(test)]
mod tests {
use super::*;
fn system_call() -> std::result::Result<(), std::ffi::NulError> {
Ok(())
}
fn windows_call() -> windows::Result<()> {
Err(Error::new(ErrorCode(777), "real bad..."))
}
fn can_fail() -> std::result::Result<(), Box<dyn std::error::Error>> {
let win_error = windows_call()?;
let std_error = system_call()?;
Ok(())
}
#[test]
fn can_mix_window_errors_with_std_errors() {
assert!(can_fail().is_err());
}
}
By having windows::Error implement the std::error::Error trait, the code above will compile which allows you to mix different kinds of errors in the same function. Something like this would work:
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message())
}
}
Is there another way to make working with different kinds of errors's easier when working with the windows crate?
Thanks for the suggestion!
What would be even better is if in addition to implementing the Error trait it was also Send + Sync. This would make it work for async code and also be compatible with the anyhow which is a commonly used crate for dealing with errors in application code.
Unfortunately IRestrictedErrorInfo contains an unsafe pointer that prevents doing this easily so that may take some careful consideration... You could consider wrapping this field in a mutex.
The OS error object (behind IRestrictedErrorInfo) does not implement IAgileObject to indicate that it is safe to be used as Send + Sync. I'm just confirming whether it is in fact thread-safe in which case we could also make it async friendly.
Did you end up determining whether the Error object can be made Send + Sync?
Yes, sorry for the delay - following up here: https://github.com/microsoft/windows-rs/issues/600#issuecomment-799426129
Most helpful comment
What would be even better is if in addition to implementing the Error trait it was also Send + Sync. This would make it work for async code and also be compatible with the anyhow which is a commonly used crate for dealing with errors in application code.
Unfortunately
IRestrictedErrorInfocontains an unsafe pointer that prevents doing this easily so that may take some careful consideration... You could consider wrapping this field in a mutex.