diff options
author | Richard Weickelt <richard@weickelt.de> | 2018-06-26 17:35:06 +0200 |
---|---|---|
committer | Simon Hausmann <simon.hausmann@qt.io> | 2018-07-02 10:43:28 +0000 |
commit | 65b831c21afa8540bf5414191988f41bedfcb409 (patch) | |
tree | c0febd17f408c5b4bc3bc315869f7f3f438ca366 /tests | |
parent | e6d19ae5cf697087bbecce9d6f702afef7c29253 (diff) |
Add QJSEngine::throwError() method to report run-time errors
It is quite common in JavaScript to use exceptions for error handling, but
there was no way to generate an exception from C++ context, i.e. when
the JS run-time invoked a C++ method or a slot.
This patch adds an naive way to report run-time errors to QJSEngine from
CPP context. The user may set a custom error message, but the location
points always to the caller context in JavaScript.
[ChangeLog][QtQml][QJSEngine] Added API to throw run-time errors.
Task-number: QTBUG-39041
Change-Id: If59627b83d50351eb225adde63187fc251aa349e
Reviewed-by: Simon Hausmann <simon.hausmann@qt.io>
Diffstat (limited to 'tests')
-rw-r--r-- | tests/auto/qml/qjsengine/tst_qjsengine.cpp | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/tests/auto/qml/qjsengine/tst_qjsengine.cpp b/tests/auto/qml/qjsengine/tst_qjsengine.cpp index 796d9e9c34..c20937f9a1 100644 --- a/tests/auto/qml/qjsengine/tst_qjsengine.cpp +++ b/tests/auto/qml/qjsengine/tst_qjsengine.cpp @@ -219,6 +219,11 @@ private slots: void protoChanges_QTBUG68369(); void multilineStrings(); + void throwError(); + +public: + Q_INVOKABLE QJSValue throwingCppMethod(); + signals: void testSignal(); }; @@ -4291,6 +4296,36 @@ void tst_QJSEngine::multilineStrings() } +void tst_QJSEngine::throwError() +{ + QJSEngine engine; + QJSValue wrappedThis = engine.newQObject(this); + QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); + engine.globalObject().setProperty("testCase", wrappedThis); + + QJSValue result = engine.evaluate( + "function test(){\n" + "try {\n" + " return testCase.throwingCppMethod();\n" + "} catch (error) {\n" + " return error;\n" + "}\n" + "return \"not reached!\";\n" + "}\n" + "test();" + ); + QVERIFY(result.isError()); + QCOMPARE(result.property("lineNumber").toString(), "3"); + QCOMPARE(result.property("message").toString(), "blub"); + QVERIFY(!result.property("stack").isUndefined()); +} + +QJSValue tst_QJSEngine::throwingCppMethod() +{ + qjsEngine(this)->throwError("blub"); + return QJSValue(47); +} + QTEST_MAIN(tst_QJSEngine) #include "tst_qjsengine.moc" |