TCL,在 catch 命令中获取完整的错误消息

TCL, get full error message in catch command

#!/usr/bin/tclsh     

proc test {} {
    aaa
}

test

当我 运行 这个脚本时,我收到错误消息:

invalid command name "aaa"
    while executing
"aaa"
    (procedure "test" line 2)
    invoked from within
"test"
    (file "./a.tcl" line 7)

如果我 运行 在 catch 中测试命令,我只会得到第一行错误消息。

#!/usr/bin/tclsh

proc test {} {
    aaa
}

catch test msg
puts $msg

这会打印: invalid command name "aaa"

是否可以在 catch 命令中获取完整的错误消息(文件、行、过程)?我的程序有很多文件,只有一行错误信息很难找到它在哪里。

简短的回答是查看 errorInfo 的值,其中将包含堆栈跟踪。

更完整的答案是查看 catch and the return 手册页并使用 -optionsVarName 参数到 catch 语句来收集提供的更详细信息。 return 手册页提供了一些关于使用它的信息。但是来自交互式会话的粗略示例:

% proc a {} { catch {funky} err detail; return $detail }
% a
-code 1 -level 0 -errorstack {INNER {invokeStk1 funky} CALL a} -errorcode NONE -errorinfo {invalid command name "funky"
    while executing
"funky"} -errorline 1
%

detail 变量是一个字典,因此使用 dict get $detail -errorinfo 获取该特定项目。