Delete or replace the absolute path of EAssertionFailed with a relative path or just the file name?

Is there a way to remove or replace the absolute path of an EAssertionFailed message? I would like not to include all the way, so as not to indirectly show where the source was compiled, and to make the message independent of this location. Preferably, the relative path to the project root or to the DPR file or only the name of the source file is indicated instead.


Program output:

EAssertionFailed: Assertion failed (C:\Users\User\Documents\
Embarcadero\Studio\Projects\Project3.dpr, line 12)

Project3.dpr

program Project3;

{$AppType Console}

{$R *.res}

uses
  System.SysUtils;

begin
  try
    Assert(False);
  except
    on E: Exception do
    begin
      WriteLn(E.ClassName, ': ', E.Message);
      ReadLn;
    end;
  end;
end.
+4
source share
1 answer

Replace or hook AssertErrorProc and change or suppress the file name and line number information.

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysConst,
  System.SysUtils;

   procedure CustomAssertErrorHandler(const Message, Filename: string; LineNumber: Integer; ErrorAddr: Pointer);

   var
      FileNameOnly : string;

   begin
      FileNameOnly := ExtractFileName(FileName);

      if Message <> '' then
        raise EAssertionFailed.CreateFmt(SAssertError,
          [Message, FileNameOnly, LineNumber]) at ErrorAddr
      else
        raise EAssertionFailed.CreateFmt(SAssertError,
          [SAssertionFailed, FileNameOnly, LineNumber]) at ErrorAddr;
   end;

begin
   AssertErrorProc := CustomAssertErrorHandler;

 try
    Assert(False);
  except
    on E: Exception do
    begin
      WriteLn(E.ClassName, ': ', E.Message);
      ReadLn;
    end;
  end;
end.

. , :

program Project3;

{$AppType Console}

{$R *.res}

uses
  System.SysConst,
  System.SysUtils;

procedure AssertErrorHandler(const Msg, Filename: String; 
  LineNumber: Integer; ErrorAddr: Pointer);

{$Region '$Include ProjectRoot.pas.inc'}

const
   ProjectRoot = 'C:\Users\';

{$EndRegion}

var
  Temp: String;

begin
  if (ProjectRoot <> '') and Filename.StartsWith(ProjectRoot) then
    Temp := Filename.Remove(0, ProjectRoot.Length)
  else
    Temp := ExtractFileName(Filename);

  if Msg <> '' then
    raise EAssertionFailed.CreateResFmt(@SAssertError,
      [Msg, Temp, LineNumber]) at ErrorAddr
  else
    raise EAssertionFailed.CreateResFmt(@SAssertError,
      [SAssertionFailed, Temp, LineNumber]) at ErrorAddr;
end;

begin
  try
    AssertErrorProc := AssertErrorHandler;
//    Assert(False);
    Assert(False, 'Custom message');
  except
    on E: Exception do
    begin
      WriteLn(E.ClassName, ': ', E.Message);
      ReadLn;
    end;
  end;
end.
+3

Source: https://habr.com/ru/post/1681629/


All Articles