문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top