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

1,98611 gold badges57 silver badges124 bronze badges

answered Mar 21, 2009 at 10:31

Daniel Rikowski's user avatar

Daniel RikowskiDaniel Rikowski

71.4k58 gold badges251 silver badges329 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

11k4 gold badges51 silver badges159 bronze badges

4

Функция GetLastError возвращает код последней возникшей в системе ошибки, которая устанавливается при вызове функций API Windows. Для того, чтобы получить текст ошибки, соответствующий коду, в Delphi можно воспользоваться функцией FormatMessage из модуля Windows.

Данная функция имеет следующий прототип:

function FormatMessage(dwFlags: DWORD; lpSource: Pointer; dwMessageId: DWORD; dwLanguageId: DWORD; lpBuffer: PChar; nSize: DWORD; Arguments: Pointer): DWORD; stdcall;

Если функции FormatMessage передать параметры GetLastError в качестве идентификатора ошибки и LPCTSTR, то она вернет текст ошибки в локализованном формате.

Ниже приведен пример кода, который получает последнюю ошибку в системе и выводит ее текст в диалоговое окно:

var LastError: DWORD; ErrorMessage: array[0..MAX_PATH] of Char;begin LastError := GetLastError; if LastError <> ERROR_SUCCESS then begin FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, nil, LastError, LANG_USER_DEFAULT, ErrorMessage, MAX_PATH, nil ); ShowMessage(ErrorMessage); end;end;

В данном примере мы используем функцию GetLastError, чтобы получить код последней ошибки, а затем передаем его в функцию FormatMessage, чтобы получить текст ошибки. Полученный текст выводится в диалоговое окно функцией ShowMessage.

Delphi TreeView Programming: RichText Formatting

Function Result Name (Obscure Syntax #5) — Delphi #154

NodeJS : seriate RequestError: SqlContext Error. Failed on step \

Don’t make this common GUI mistake — Delphi #214

Obscure ^C Syntax — Delphi #130

Using reFind to fix delphi-hlp.rus warning — Delphi #121

how to install delphi — how to download delphi for free — how to download delphi community edition

Ошибка при установке Delphi 2014 Unknown error during init

Windows : windows service command RPC error (delphi-hlp.ru or psservice)

Delphi #179 — TZipFile FileComment Bug

SPECIAL OFFER        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

 
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)


Author: Embarcadero USA

 Technical Information Database

TI2459C.txt   Displaying an error string from GetLastError.
Category   :General
Platform    :All
Product    :Borland C++  All

Description:
   Displaying an Error Message with GetLastError
   GetLastError is a WIN32 API that returns an error code indicating
   the most recent error. The most recent error will be set by the
   failing function. For example, if a call to LoadLibrary fails,
   LoadLibrary will call SetLastError. The error code returned by
   GetLastError can be found in WINERROR.H but another WIN32 API,
   FormatMessage, has built-in support for retrieving an appropriate
   error message string.
   FormatMessage is used to build up a message string given a number of
   options such as language. The source for the message can be a buffer
   or string resource found within a module. Additionally, FormatMessage
   supports a flag that will read the string from an operating system
   message table. The necessary flag is FORMAT_MESSAGE_FROM_SYSTEM.
   The following sample demonstrates using FormatMessage to allocate
   and fill a buffer with the most recent error ( returned by a call
   to GetLastError ). This example was built as a console mode application
   with the command line:
     bcc32 test.cpp
   Of course, in a WIN32 GUI application the buffer could be used in a
   call to MessageBox.
#include 
#include 
int main()
{
 LPVOID ptr = 0;
// try a sure-to-fail API call such as one of the following
   LoadLibrary("sijvoaisjv"); // "library file...cannot be found"
// LoadLibrary((char*)1234); // "The parameter is incorrect"
 FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ),
                (LPTSTR)&ptr,
                0, NULL);
 cout <<

Article originally contributed by Borland Staff

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Delphi findclose ошибка
  • Delphi copyfile коды ошибок
  • Delphi assignfile ошибка
  • Defect acculading ошибка рено меган 2
  • Delphi 7 unable to rename delphi32 ошибка

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

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