Write log of system exceptions using application events

1

I want to write to any text file any exception that happens in the system.

I'm using the Application Events component of the additional palette.

Below is an 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 onException event of the component.

    
asked by anonymous 08.04.2016 / 15:50

1 answer

1

Create a unit with the code that logs it and calls it from the try...Except that handles the error and does not 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 try...Except was:

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