Windows-rs: Question: GetLastError and human readable message

Created on 24 Feb 2021  ·  3Comments  ·  Source: microsoft/windows-rs

When some Win32 functions fail they will return 0 which indicates that we need to check GetLastError in order to attain the last error code. We can then subsequently call FormatMessageW if we want a human readable error message.

Is this process still the same using windows-rs?
Are there any helper functions to assist?

For example in C++ we can use the std::error_code (with std::system_category) to convert the error code returned from GetLastError into a human readable string.

question

All 3 comments

WinRT methods all return std::result::Result<T, windows::Error> aka windows::Result.

Some COM and Win32 functions return either windows::ErrorCode (an HRESULT) or windows::BOOL. Both of these provide ok() methods that turn the result into windows::Result. This is useful for short-circuiting with ?. There are plenty of examples of this in the examples.

You can also directly create windows::ErrorCode based on the error code stored on the calling thread via ErrorCode::from_thread. This calls GetLastError under the hood.

The windows::ErrorCode doesn't provide a way to retrieve a message. Perhaps it should.

windows::Error doesn't provide a from_thread method, but I plan to add one. It does however provide a message() method that will call FormatMessage under the hood.

For now, you can do this:

let e = Error::fast_error(ErrorCode::from_thread());

println!("{:?}", e);
println!("{} {}", e.code().0, e.message());

Output:

Error { code: 0x00000000, message: "The operation completed successfully." }
0 The operation completed successfully.

All of the functions I have used thus far return a DWORD (u32) which either indicates the count of something (ex. number of characters copied into the output buffer) or 0 if an error occurred. In the case of a 0 return I would typically call GetLastError.

The snippet you provided is perfect, thanks you.

ErrorCode now provides a message method directly.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ctaggart picture ctaggart  ·  4Comments

Zymlex picture Zymlex  ·  3Comments

ZCWorks picture ZCWorks  ·  3Comments

rylev picture rylev  ·  4Comments

kennykerr picture kennykerr  ·  5Comments