Friday, October 22, 2010

A helpful exception class

Many times you find out yourself writing exceptions with many conversions, I do it this way:


unit BB.Exceptions;

interface

uses
  SysUtils;

type
  EExceptionEx = class(Exception)
  public
    constructor Create(const aMessage: string; const aParam: array of variant); virtual;
  end;

  ETooManyObjects = class(EExceptionEx);
  ETimeOut = class(EExceptionEx);
  EDatabaseException = class(EExceptionEx);
  EUserException = class(EDatabaseException);
  ECompanyException = class(EDatabaseException);
  EServerException = class(EDatabaseException);
  EDataSetException = class(EDatabaseException);
  EConexionNotFound = class(EDatabaseException);

implementation

{ EExceptionEx }

constructor EExceptionEx.Create(const aMessage: string; const aParam: array of variant);
var
  n: integer;
  Text: string;

begin
  Text := aMessage;
  for n := Low(aParam) to High(aParam) do
    Text := StringReplace(Text, '%' + IntToStr(n + 1), string(aParam[n]), []);

  inherited Create(Text);
end;

end.
So is easy to write something like:
raise EExceptionEx.Create('Invalid server %1, date %2, dummy %3', ['SRV123', Now, 1]);
And you can forget about conversions...

No comments:

Post a Comment