[Interest] QJSEngine: throwing errors from C++ code.

Martijn van der Kwast mvdkwast at gmail.com
Thu Apr 30 11:05:18 CEST 2015


Hi,

I'm exporting some functions to the JS environment in which an error may
occur. I'd like to get that error back to the JS environment as an
exception. I first posted this question on
https://forum.qt.io/topic/52437/catching-error-thrown-in-c-code-in-js, but
was redirected here.

class Math : public QObject
{
    Q_OBJECT
public:
    Math(QObject *parent=0);

    Q_INVOKABLE void Sqrt(int arg) {
        if (arg < 0) {
            // Do something here that causes an exception in the js
environment
            throw "InvalidArgException";
        }
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
    QJSEngine eng(&app);
    Math math(&app);
    eng.globalObject().setProperty("Math", eng.newQObject(&math));
    eng.evaluate("try { Math.Sqrt(-1); } catch(e) { console.log(e); }");
}

The following code found in tests/auto/qml/qqmlecmascript/testtypes.cpp
would do the trick, unfortunately, this requires the use of internals.
Maybe a method could be added to the QJSEngine public API to wrap
engine()->currentContext()->throwError() ?

void MyQmlObject::v8function(QQmlV4Function *function){
    V8Engine::getV4(function->engine())->currentContext()->throwError(QStringLiteral("Exception
thrown from within QObject slot"));
}

Or did I miss a way to accomplish that with the current API ?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20150430/4fd3aacb/attachment.html>


More information about the Interest mailing list