使用相对路径或文件名删除或替换EAssertionFailed的绝对路径?

时间:2017-07-17 16:51:26

标签: delphi pascal

是否有某种方法可以删除或替换EAssertionFailed错误消息的绝对路径?我想不包括整个路径,以不间接地揭示源编译的位置,并使消息独立于该位置。优选地,项目根目录或DPR文件的相对路径或源文件名仅包含在错误消息中。

节目输出:

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.

1 个答案:

答案 0 :(得分:3)

替换或挂钩AssertErrorProc并更改或禁止文件名和行号信息。

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.