【发布时间】:2016-12-30 18:03:45
【问题描述】:
当从QML 中的JavaScript 函数调用C++ 中编写的Q_INVOKABLE 方法时,如何抛出异常?该方法由 < MyApp > 类型的对象拥有,并通过调用 qmlRegisterType() 注册
例如,我有以下 QML 代码:
TextField {
id: fld_recipient
onEditingFinished: {
try {
var identity=myapp.identities.current_Identity;
var company=identity.companies.current_Company;
myapp.lookup_email(identity.identity_id,company.company_id,fld_recipient.text)
} catch(e) {
console.log(e);
}
}
}
这里,方法 MyApp::lookup_email() 进入服务器并搜索匹配的电子邮件地址。这个过程可能会因大量错误而停止,我希望 catch() 语句显示该错误。
这是如何在 C++ 端完成的?有点像这样:
void MyApp::lookup_email(int identity_id,int company_id,QString email) {
....
error_code=server->lookup_email(identity_id,company_id,email);
if (error_code) { /// throw an exception to QML engine,
????? <= what goes here ?
}
}
【问题讨论】:
-
如果发生错误则返回一个空字符串,并在QML中检查该字符串是否真的包含电子邮件。
-
老实说,我不会费心处理异常,只需使用经典的返回码。这甚至与技术无关,但就我而言,我无法想象自己在一年前考虑某个项目 - 哦该死的......这个异常来自哪里以及它在哪里处理=)
-
@evilruff,我想让它对将要使用我的组件的 JavaScript 开发人员更友好。 Q_INVOKABLE C++ 方法依赖于其他变量,例如,如果它们为 NULL,我想抛出一个 TypeError 说某个变量是“未定义”
-
你有没有得到这个答案?我试图做同样的事情......