NLESC-JCER / cpp2wasm

Guide to make C++ available as a web application
https://nlesc-jcer.github.io/cpp2wasm/
Apache License 2.0
22 stars 6 forks source link

Exception handling #28

Open sverhoeven opened 4 years ago

sverhoeven commented 4 years ago

As a C++ developer I sometimes throw an exception from my C++ code. I would like to know how to handle the exception in Python and JavaScript.

For example in the while loop I could add a max iterations threshold and throw an exception when the algorithm does not converge in time.

sverhoeven commented 4 years ago

In JavaScript you will catch a long number which can be converted to the error message with:

// Normally thrown exceptions will be a long in js-space
// the long is a function pointer which in c++-space can be asked for the what message
std::string error_message(intptr_t pointer) {
    auto error = reinterpret_cast<std::runtime_error *>(pointer);
    return error->what();
}

The binding for it would be

function("error_message", &error_message, allow_raw_pointers());
sverhoeven commented 4 years ago

For WebAssembly moduile add -s DISABLE_EXCEPTION_CATCHING=0 to emcc command otherwise exceptions are swallowed.