pax*_*blo 4 error-handling qt declarative qml
我的 QML 文件中有一个(声明性)行记录错误,我想捕获它并记录某些变量以尝试找出发生了什么。该行类似于(包含在 aRepeater因此使用index):
a: ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c
Run Code Online (Sandbox Code Playgroud)
(不,这些不是我的实际变量名,我已经重命名它们以防止信息泄漏 - 实际名称并不重要)。
运行代码时,我偶尔会收到错误:
file:///path/to/SomeFile.qml:7: TypeError: Cannot read property 'c' of undefined
Run Code Online (Sandbox Code Playgroud)
让我相信当a基于其他变量修改字段时,这些变量之一在某种程度上是错误的。
我知道try/catch在程序QML 代码中,但我不确定如何为声明性代码做类似的事情(或者即使可能)。
有没有办法捕获该错误并打印出发生错误时存在的所有相关变量?
也许我不理解这个问题,但a:赋值可以是一个函数的结果,甚至只是一个返回一些值的 JS 代码块。所以你可以自由地使用 try/catch 或其他任何东西。
a: {
try {
return ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c;
}
catch(e) {
console.log(e);
return "FUBAR";
}
}
Run Code Online (Sandbox Code Playgroud)
添加:return关键字在这里实际上是可选的,没有它们也能正常工作。
还要指出的是:
a: ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c;
与:
a: { ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c; }
对于单行表达式,花括号只是可选的。