Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top