當方法呼叫產生錯誤時,許多函式都會傳回錯誤碼。 對於大多數傳回錯誤碼的憑證服務介面和 API 元素,呼叫 具有 NULL 模組句柄的 FormatMessage,即可擷取錯誤訊息正文。 如果 FormatMessage 不成功,錯誤碼很可能是因為備份 API 元素或資料庫相關錯誤所造成;使用對應至 Ntdsbmsg.dll 連結庫的模組句柄呼叫 formatMessage 應該擷取錯誤訊息正文。 下列範例示範如何在憑證服務應用程式中擷取錯誤訊息文字。
#include <windows.h>
#include <stdio.h>
// Display error message text, given an error code.
// Typically, the parameter passed to this function is retrieved
// from GetLastError().
void PrintCSBackupAPIErrorMessage(DWORD dwErr)
{
WCHAR wszMsgBuff[512]; // Buffer for text.
DWORD dwChars; // Number of chars returned.
// Try to get the message from the system errors.
dwChars = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwErr,
0,
wszMsgBuff,
512,
NULL );
if (0 == dwChars)
{
// The error code did not exist in the system errors.
// Try Ntdsbmsg.dll for the error code.
HINSTANCE hInst;
// Load the library.
hInst = LoadLibrary(L"Ntdsbmsg.dll");
if ( NULL == hInst )
{
printf("cannot load Ntdsbmsg.dll\n");
exit(1); // Could 'return' instead of 'exit'.
}
// Try getting message text from ntdsbmsg.
dwChars = FormatMessage( FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_IGNORE_INSERTS,
hInst,
dwErr,
0,
wszMsgBuff,
512,
NULL );
// Free the library.
FreeLibrary( hInst );
}
// Display the error message, or generic text if not found.
printf("Error value: %d Message: %ws\n",
dwErr,
dwChars ? wszMsgBuff : L"Error message not found." );
}