I have a problem using a third-party component in Delphi 2006 (also Delphi 7), in which I get an «Unspecified Error» when executing a function call to that component. Do you have example code that utilises GetLastError and FormatMessage in Delphi, that would allow me to access more information about the error ? TIA
asked Mar 21, 2009 at 10:10
3
There is an integrated helper function in Delphi: SysErrorMessage
. It’s essentially a wrapper to FormatMessage
, but much simpler to use in your case. Just provide the error code you need a textual description for.
For example you can use this to display the last error:
ShowMessage(SysErrorMessage(GetLastError))
If you want to raise an exception with this message, it’s even simpler:
RaiseLastOSError;
Important: Make sure that there is no additional API call between the failing function and your call of GetLastError
, otherwise the last error will be reset.
Grim
2,79010 gold badges56 silver badges120 bronze badges
answered Mar 21, 2009 at 10:31
Daniel RikowskiDaniel Rikowski
71k57 gold badges250 silver badges325 bronze badges
1
While DR is correct, there is a problem with this approach: It does not allow you to specify the context in which the error occurred. Ever seen the error «An API function failed.» whithout being any wiser which function it was and where it happended?
That’s why I wrote the RaiseLastOsErrorEx and Win32CheckEx functions:
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;
(They are part of unit u_dzMiscUtils of my dzLib library available here:
https://osdn.net/projects/dzlib-tools/svn/view/dzlib/trunk/src/u_dzMiscUtils.pas?view=markup&root=dzlib-tools#l313
answered Jul 13, 2009 at 7:30
dummzeuchdummzeuch
10.9k4 gold badges51 silver badges157 bronze badges
4
Order and save right now! 20% off with the 729824315 dicscount code for Ultimate Pack and any another product for Delphi from Greatis Programming! |
Use GetLastError function to get code of the last error and SysErrorMessage function to convert this code to string.
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(SysErrorMessage(GetLastError));
end;
Download source code
-
More for developers
-
●
Delphi Components●
.Net Components●
Software for Android Developers●
Databases for Amazon Associates
Amazon Categories
Amazon Nodes
Функция RTL SysErrorMessage(GetLastError).
Code: |
procedure TForm1.Button1Click(Sender: TObject); begin {Cause a Windows system error message to be logged} ShowMessage(IntToStr(lStrLen(nil))); ShowMessage(SysErrorMessage(GetLastError)); end; |
- Подробности
- Родительская категория: Windows
- Категория: Программирование без VCL, работа с WinAPI
Добавить комментарий
← →
VIB
(2002-10-01 13:32)
[0]
Подскажите как из Delphi получить сообщение об ошибке код которой
генерирует функция GetLastError().
Мы используем функцию FormatMessage() но что-то не получается.
Если можно фрагмент кода.
Заранее благодарен.
← →
MBo
(2002-10-01 14:16)
[1]
var ErrStr:Pchar;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,
nil,GetLastError,LANG_USER_DEFAULT,@ErrStr,0,nil);
Caption:=ErrStr;
← →
VIB
(2002-10-01 14:49)
[2]
Большое спасибо MBo все получилось.
← →
SPeller
(2002-10-01 21:19)
[3]
2 MBo © (01.10.02 14:16)
А освобождать строку не надо?
← →
Юрий Зотов
(2002-10-01 22:24)
[4]
Посмотрите также RaiseLastWin32Error и Win32Check. Во многих случаях упрощают дело.
← →
Pat
(2002-10-01 22:35)
[5]
SysErrorMessage(GetLastError)