Log system exceptions using application events

Asked

Viewed 1,378 times

1

I am wanting to record in a text file any exception that happens on the system.

I’m using the component Application Events of the Additional palette.

Below follows the example of the code:

procedure TfmPrototipo.ApplicationEventsException(Sender: TObject; 

E:Exception);
var
  NomeArquivo: string;
  Arquivo: TextFile;

begin

  NomeArquivo := ChangeFileExt(Application.Exename, '.log');
  AssignFile(Arquivo, NomeArquivo);
  if FileExists(NomeArquivo) then 
    Append(arquivo) 
  else 
    ReWrite(arquivo); 
  try 
    WriteLn(arquivo, 'Data: '+ DateTimeToStr(Now));
    WriteLn(arquivo, 'Erro: ' + E.Message );
    WriteLn(arquivo, '------------------------------------------- ');
    Application.ShowException(E);
  finally 
    CloseFile(arquivo); 
  end;

end;

The problem that in some screens of the systems is used the try - except, it displays the message and does not call the event onException of the component.

  • I’m not aware of Delphi specifically, but in general Application Events is a global capturer of Exception not handled by the system, i.e., the ones that will generate crash in the system, the unknown problems in development. Already the errors where you use the try - except, are errors that you have already predicted in the development and possibly treated them in some way, so if this Exception is not propagated, it will not be captured by Application Events. So if despite treating the exception you want to log the same you should do it on except of try - except.

1 answer

1

Create a Unit with the code that logs and calls it from try...Except that treats error and does not make a raise.

Example:

procedure FazLogException(NomeArquivo: string; E:Exception);
var
  Arquivo: TextFile;
begin
  AssignFile(Arquivo, NomeArquivo);
  if FileExists(NomeArquivo) then 
    Append(arquivo) 
  else 
    ReWrite(arquivo); 
  try 
    WriteLn(arquivo, 'Data: '+ DateTimeToStr(Now));
    WriteLn(arquivo, 'Erro: ' + E.Message );
    WriteLn(arquivo, '------------------------------------------- ');
  finally 
    CloseFile(arquivo); 
  end;
end;

Now just call in the place where was the try...Except:

try
  b := 0;
  a := 12 div b;
except
  on E: Exception do
  begin
    FazLogException(ChangeFileExt(Application.Exename, '.log'), E);
    ShowMessage(E.Message);
  end;
end;
  • 1

    @Caputo mentioned in the question that the system already does so and does not raise the exception. Then use a raise would change the behavior of the program.

  • I hadn’t seen this part. Vlw... Removing the comment :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.