gpt4 book ai didi

delphi - 删除 EAssertionFailed 的绝对路径或将其替换为相对路径或仅文件名?

转载 作者:行者123 更新时间:2023-12-03 15:30:13 26 4
gpt4 key购买 nike

是否有某种方法可以删除或替换 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.

最佳答案

替换或 Hook 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.

关于delphi - 删除 EAssertionFailed 的绝对路径或将其替换为相对路径或仅文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com