Compartir a través de


Recuperación de mensajes de error

Cuando una llamada al método genera un error, muchas funciones devuelven un código de error. Para la mayoría de las interfaces y elementos de API de Servicios de certificados que devuelven un código de error, el texto del mensaje de error se puede recuperar llamando a FormatMessage con un identificador de módulo NULL. Si FormatMessage no tiene éxito, lo más probable es que el código de error haya sido provocado por un elemento de API de copia de seguridad o un error relacionado con la base de datos; al llamar a FormatMessage con un identificador de módulo correspondiente a la biblioteca de Ntdsbmsg.dll, debería recuperar el texto del mensaje de error. En el ejemplo siguiente se muestra cómo recuperar el texto del mensaje de error en una aplicación de Servicios de certificados.

#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." );

}