Dre*_*son 25 delphi error-handling winapi
我在Delphi 2006(也是Delphi 7)中使用第三方组件时遇到问题,在执行对该组件的函数调用时,我得到一个"未指定的错误".你有使用Delphi中的GetLastError和FormatMessage的示例代码,这将允许我访问有关错误的更多信息吗?TIA :)
Dan*_*ski 60
Delphi中有一个集成的辅助函数:SysErrorMessage.它本质上是一个包装器FormatMessage,但在您的情况下使用起来要简单得多.只需提供您需要的文本描述的错误代码.
例如,您可以使用它来显示上一个错误:
ShowMessage(SysErrorMessage(GetLastError))
Run Code Online (Sandbox Code Playgroud)
如果您想使用此消息引发异常,则更简单:
RaiseLastOSError;
Run Code Online (Sandbox Code Playgroud)
重要提示:确保在失败的功能和您的调用之间没有额外的API调用GetLastError,否则将重置最后一个错误.
虽然DR是正确的,但这种方法存在问题:它不允许您指定发生错误的上下文.曾经见过错误"API函数失败".没有任何更明智的功能,它在哪里发生了什么?
这就是我编写RaiseLastOsErrorEx和Win32CheckEx函数的原因:
procedure RaiseLastOsErrorEx(const _Format: string);
begin
RaiseLastOsErrorEx(GetLastError, _Format);
end;
procedure RaiseLastOsErrorEx(_ErrorCode: integer; _Format: string); overload;
var
Error: EOSError;
begin
if _ErrorCode <> ERROR_SUCCESS then
Error := EOSError.CreateFmt(_Format, [_ErrorCode, SysErrorMessage(_ErrorCode)])
else
Error := EOsError.CreateFmt(_Format, [_ErrorCode, _('unknown OS error')]);
Error.ErrorCode := _ErrorCode;
raise Error;
end;
function GetLastOsError(out _Error: string; const _Format: string = ''): DWORD;
begin
Result := GetLastOsError(GetLastError, _Error, _Format);
end;
function GetLastOsError(_ErrCode: integer; out _Error: string; const _Format: string = ''): DWORD;
var
s: string;
begin
Result := _ErrCode;
if Result <> ERROR_SUCCESS then
s := SysErrorMessage(Result)
else
s := _('unknown OS error');
if _Format <> '' then
try
_Error := Format(_Format, [Result, s])
except
_Error := s;
end else
_Error := s;
end;
function Win32CheckEx(_RetVal: BOOL; out _ErrorCode: DWORD; out _Error: string;
const _Format: string = ''): BOOL;
begin
Result := _RetVal;
if not Result then
_ErrorCode := GetLastOsError(_Error, _Format);
end;
Run Code Online (Sandbox Code Playgroud)
(它们是我的dzLib库的单元u_dzMiscUtils的一部分:https://sourceforge.net/p/dzlib/code/HEAD/tree/dzlib/trunk/src/u_dzOsUtils.pas
| 归档时间: |
|
| 查看次数: |
23974 次 |
| 最近记录: |