Sal*_*dor 8 delphi error-handling winapi wininet
我需要获取WinInet函数错误代码的描述,关于WinInet函数的MSDN文档说明GetLastError
当函数失败时我必须使用该函数来检索最后的错误代码.现在,当我查看有关该GetLastError
功能的文档说.
.要获取系统错误代码的错误字符串,请使用 FormatMessage函数
我检查哪个SysErrorMessage
delphi函数在内部调用FormatMessage winapi函数,所以我使用该函数来检索错误描述,但是不起作用(我的意思是不返回WinInet错误代码的描述)我在Delphi 2007中测试了这段代码和Delphi XE.
看到这段代码
uses
Wininet, Windows, SysUtils;
procedure TestWinInet(const AUrl : string);
var
hInter,hRemoteUrl : HINTERNET;
Code : Cardinal;
begin
hInter := InternetOpen(PChar('Explorer 5.0'), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if hInter=nil then
begin
Code:=GetLastError;
raise Exception.Create(Format('Error %d Description %s',[Code,SysErrorMessage(Code)]));
end;
try
hRemoteUrl := InternetOpenUrl(hInter, PChar(AUrl), nil, 0, INTERNET_FLAG_RELOAD, 0);
if hRemoteUrl=nil then
begin
Code:=GetLastError;
raise Exception.Create(Format('Error %d Description %s',[Code,SysErrorMessage(Code)]));
end;
try
//do something else
finally
InternetCloseHandle(hRemoteUrl);
end;
finally
InternetCloseHandle(hInter);
end;
end;
begin
try
//i am passing a invalid url just to raise the error
TestWinInet('Foo');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,返回代码12006,其定义为ERROR_INTERNET_UNRECOGNIZED_SCHEME
和相关的描述 The URL scheme could not be recognized or is not supported.
所以问题是 How I can retrieve the error description for the WinInet error codes in delphi?
Erv*_*inS 11
我认为你应该尝试直接使用FormatMessage,因为你需要告诉错误代码的来源.我找到了这个有效的代码.
class function TCertificateManager.GetLastErrorText: string;
var
code: DWORD;
Len: Integer;
Buffer: array[0..255] of Char;
begin
code := GetLastError();
Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM,
Pointer(GetModuleHandle('Advapi32.dll')), code, 0, Buffer, SizeOf(Buffer), nil);
while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len);
SetString(Result, Buffer, Len);
end;
Run Code Online (Sandbox Code Playgroud)
您应该进行一些更改,可能使用'wininet.dll'而不是Advapi32.dll,但它应该可以工作.
UPDATE
这是WinInet功能的版本
function GetWinInetError(ErrorCode:Cardinal): string;
const
winetdll = 'wininet.dll';
var
Len: Integer;
Buffer: PChar;
begin
Len := FormatMessage(
FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_IGNORE_INSERTS or FORMAT_MESSAGE_ARGUMENT_ARRAY,
Pointer(GetModuleHandle(winetdll)), ErrorCode, 0, @Buffer, SizeOf(Buffer), nil);
try
while (Len > 0) and {$IFDEF UNICODE}(CharInSet(Buffer[Len - 1], [#0..#32, '.'])) {$ELSE}(Buffer[Len - 1] in [#0..#32, '.']) {$ENDIF} do Dec(Len);
SetString(Result, Buffer, Len);
finally
LocalFree(HLOCAL(Buffer));
end;
end;
Run Code Online (Sandbox Code Playgroud)