Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using TApplicationEvents In A Program

Status
Not open for further replies.

ajbufort

Programmer
Apr 4, 2004
50
US
Hello All,

Trying to implement global exception handling in a service, but I can't seem to get it to work. Is there something I'm missing?

I am trying to do the following:

Code:
ApplicationEvents := TApplicationEvents.Create(nil);
ApplicationEvents.OnException := LogException;

in my ServiceExecute, and:

Code:
TMMRS_tony = class(TService)
  procedure ServiceExecute(Sender: TService);
public
  procedure LogException(Sender: TObject; E: Exception);
  function GetServiceController: TServiceController; override;
end;

under 'Type'.

The logging procedure itself is:

Code:
procedure TMMRS_tony.LogException( Sender: TObject; E: Exception );
var
  Filename: string;
  LogFile: TextFile;
begin
  Filename := ChangeFileExt ('RelayServer','.log');
  AssignFile (LogFile, Filename);
  
  if FileExists (FileName) then
    Append (LogFile)
  else
    Rewrite (LogFile);

  try
    Writeln (LogFile, DateTimeToStr (Now) + ':' + E.Message);
  finally
    CloseFile (LogFile);
  end;
end; (* LogException *)

What am I doing wrong? I know that, since this is a service, things might work a bit differently, so how would I do it then?

Also, how would I do it for ANY non-VCL program.

Thanks,

-Tony
 
Hi Tony,

in a service you don't have the TApplication object on which TApplicationEvents depends. so your approach won't work. I write my service functions so that they never can't throw exceptions.

like this :

procedure TMyServiceThread.WhatEver;
begin
try
try
//allocate objects
..
finally
//deallocate objects
..
end;
except
on E : Exception do
LogException('WhatEver',E.Message);
end;
end;

I use this framework in EVERY procedure/function. I found this an easy way to quickly find bugs.

cheers

--------------------------------------
What You See Is What You Get
 
Hi whosrdaddy,

Thanks very much for your response. I will take the approach you suggested.

-Tony
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top