UEFI TIps:格式化GetLastError 结果的 FormatMessage

通常我们使用 GetLastError 来获得API 的错误代码,在取得之后还需要查表。其实可以直接使用FormatMessage 这个 API ,将错误代码转为错误的信息输出。

本文代码来自 https://www.cnblogs.com/passedbylove/p/6088096.html

static void
win32perror(const TCHAR *s)
{
	LPVOID buf;
	if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS
		| FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR)&buf,
		0,
		NULL)) {
		_ftprintf(stderr, _T("%s: %s"), s, buf);
		fflush(stderr);
		LocalFree(buf);
	}
	else
		_ftprintf(stderr, _T("%s: unknown Windows error\n"), s);
}

 

在使用的地方申明 TCHAR *wSZError = _T(“error message \n”);

调用上面的函数 win32perror(wSZError); 即可.

微软也提供了一个类似的例子 https://docs.microsoft.com/en-us/windows/desktop/Debug/retrieving-the-last-error-code

void ErrorExit(LPTSTR lpszFunction)
{
	// Retrieve the system error message for the last-error code

	LPVOID lpMsgBuf;
	LPVOID lpDisplayBuf;
	DWORD dw = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		dw,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR) &lpMsgBuf,
		0, NULL);

	// Display the error message and exit the process

	lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
		(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
	StringCchPrintf((LPTSTR)lpDisplayBuf,
		LocalSize(lpDisplayBuf) / sizeof(TCHAR),
		TEXT("%s failed with error %d: %s"),
		lpszFunction, dw, lpMsgBuf);
	//MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

	LocalFree(lpMsgBuf);
	LocalFree(lpDisplayBuf);
	ExitProcess(dw);
}

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注