Handling errors in C++ code of QML application

Viewed 210

I'm working on a project which involves QML UI and heavy C++ logic. Most parts of our codebase use C++ exceptions for error handling. And my main question is, how can I automate translation of these C++ exceptions to QML errors?

The only relevant link I found is Global exception handling with c++/QML which just states one needs to pass errors as return values manually. Or wrap them with try-catch blocks on QML side, again manually.

Some more details and context.

When I worked on QWidgets-based application, I could simply override QCoreApplication::notify and handle all unhandled otherwise errors there. As for QML engine, it doesn't seem to be exception-neutral. Stack unwinding through it causes access violations and other unpleasant runtime errors. And there seems to be no extension point similar to QCoreApplication::notify. Closest functions QQmlObjectOrGadget::metacall and static CallMethod in qv4qobjectwrapper.cpp:1270 are buried deep in implementation and cannot be augmented without patching Qt.

QML documentation also suggests QJSEngine::throwError as a way to produce QML exceptions from C++ code. Problem is, it requires instance of QML engine, which can be obtained through QQmlEngine::contextForObject(...)->engine() or qmlEngine. Which can be used only on objects handled by QML. So if you call arbitrary Q_INVOKABLE method on C++ object exposed to Qt, you have no easy access to QQmlEngine instance.

The last part, which is capturing unhandled QML exceptions, seems to be more manageable through QQmlEngine::warnings signal.

0 Answers
Related