Domanda

GetLastError() can be somehow passed to FormatMessageW to get a formatted message. The objective is to get a QString at the end. What is the correct and safe way of doing it?

È stato utile?

Soluzione

This does the trick.

QString getLastErrorMsg() {
    LPWSTR bufPtr = NULL;
    DWORD err = GetLastError();
    FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                   FORMAT_MESSAGE_FROM_SYSTEM |
                   FORMAT_MESSAGE_IGNORE_INSERTS,
                   NULL, err, 0, (LPWSTR)&bufPtr, 0, NULL);
    const QString result = 
        (bufPtr) ? QString::fromUtf16((const ushort*)bufPtr).trimmed() :
                   QString("Unknown Error %1").arg(err);
    LocalFree(bufPtr);
    return result;
}

One should always specify FORMAT_MESSAGE_IGNORE_INSERTS when calling FormatMessage. Some error messages do contain placeholders, which will lead to bugs, unless your code passes an argument list. Since we're passing NULL this would be bug waiting to happen.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top