Меню

Delphi getlasterror текст ошибки

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

Drew Gibson's user avatar

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's user avatar

Grim

3,3109 gold badges55 silver badges117 bronze badges

answered Mar 21, 2009 at 10:31

Daniel Rikowski's user avatar

Daniel RikowskiDaniel Rikowski

70.2k57 gold badges250 silver badges324 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

dummzeuch's user avatar

dummzeuchdummzeuch

10.8k3 gold badges52 silver badges156 bronze badges

4

From RAD Studio API Documentation

Jump to: navigation, search

  • Up to Parent: System

Delphi

function GetLastError: Integer; stdcall;

Contents

  • 1 Properties
  • 2 Description
    • 2.1 See Also
    • 2.2 Code Examples

Properties

Type Visibility Source Unit Parent
function external public WindowsAPIs.INC System System

Description

Returns the last error reported by an operating system API call.

GetLastError returns the last error reported by an API call into the operating system. Calling this function usually resets the operating system error state.
The GetLastError function returns an error code from the operating system. After that, when calling SysErrorMessage on that error code, GetLastError will return a string with a formatted error message associated with the error code.

See Also

  • Win32Check
  • SysErrorMessage

Code Examples

  • LastOSError (Delphi)
  • LastOSError (C++)

Retrieved from «http://docwiki.embarcadero.com/Libraries/Sydney/e/index.php?title=System.GetLastError&oldid=624751»

Category:

  • API Documentation

 
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)


0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Df032 ошибка рено меган 3