Reputation: 765
In my tiny little Rust program, I'm calling a Windows API and want to make sure that everything went OK. In order to do so, I'm using the functionality provided by std::io::Error::last_os_error()
. I also want to deliberately ignore some of the errors that may occur.
I could not find any information on how to do that, other than just printing out the Error
returned by that function. What I actually need is a kind of a match statement in which I can handle the various known errors.
I understand that the function returns an std::io::Error
struct but I could not find any information on error IDs or similar concepts.
Currently, my code reads like
use std::io::Error;
fn main() {
// do some stuff that may lead to an error
match Error::last_os_error() {
163 => // Do nothing. This error is to be expected
// _ => Err("Something went wrong "),
}
}
The actual problem is that last_os_error()
returns an error struct but I want to match on the ID of the error that is listed in WinError.h (this program only runs under Windows).
Can anybody help me on how to distinguish the various errors behind the error structs in such a match statement?
Upvotes: 2
Views: 1571
Reputation: 432239
You can use io::Error::raw_os_error
to get the original error code and then match against that:
match Error::last_os_error().raw_os_error() {
Some(163) => {} // Do nothing. This error is to be expected
Some(e) => panic!("Unknown OS error {}", e),
None => panic!("Not an OS error!"),
}
It's a different question of whether this is a good idea or not. You can also match against known error types. I'd recommend using that where possible. You may also want to create (or find) an enum that maps the various error codes to human-readable values, as it's a lot easier to tell that you meant NotEnoughMemory
instead of SecurityDescriptorInvalid
than it is to tell the difference of 123
and 132
.
Upvotes: 2