你能捕捉到 QML 声明代码中的错误吗?

Can you catch errors in QML declaritive code?

我的 QML 文件中有一行(声明性)记录错误,我想捕获它并记录某些变量以尝试找出发生了什么。该行类似于(包含在 Repeater 中,因此使用 index):

a: ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c

(不,这些不是我的 实际 变量名称,我已重命名它们以防止信息泄漏 - 实际名称并不重要)。

当运行代码时,我偶尔会得到错误:

file:///path/to/SomeFile.qml:7: TypeError: Cannot read property 'c' of undefined

让我相信,当 a 字段根据其他变量进行修改时,其中一个变量在某种程度上是错误的。

我知道 procudural QML 代码中的 try/catch 但我不确定如何为声明性代码做类似的事情(或者即使它可能)。

有没有办法捕获该错误并打印出错误发生时存在的所有相关变量?

也许我不明白这个问题,但是 a: 赋值可以是一个函数的结果,甚至可以是 returns 一些值的 JS 代码块。因此,您可以自由使用 try/catch 或其他任何东西。

a: {
  try {
    return ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c;
  } 
  catch(e) {
    console.log(e);
    return "FUBAR";
  }
}

ADDEDreturn 关键字在这里实际上是可选的,与 w/out 它们一样有效。

还要指出:

a: ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c;

等同于:

a: { ((n === -1) || (n - p > 7) || (index >= t)) ? "" : b[p+index].c; }

大括号对于单行表达式来说是可选的。