简体   繁体   中英

Emscripten: How to catch JS exception?

Emscripten 'val.h' API allows calling methods of JS objects, however, C++ try-catch won't catch JS exception. Consider this example:

#include <emscripten.h>
#include <emscripten/val.h>

void test(){
    string t = "some invalid json";
    val    v = val::object();

    // This C++ try-catch doesn't catch JS exception
    try {
        v = val::global("JSON").call<val>("parse", t);
        cout <<"ok" <<endl;
    }
    catch(...){
        cout <<"failed" <<endl;
    }

    cout <<"ret" <<endl;
}

The JS exception makes the 'test' function stop and no ok , no failed , no ret printed out. How to catch that JS exception thrown by JSON.parse ?

There's 1 issue here but it's still open: https://github.com/emscripten-core/emscripten/issues/11496

Based on documentation :

By default, exception catching is disabled in Emscripten.

You have to enable it with the -fexceptions argument.

Emscripten doesn't seem to be able to catch JS exceptions in C++ yet. Here's a work-around:

// extern_pre.js
function json_parse(str){
    try{
        return JSON.parse(str);
    }
    catch(E){
        return null;
    }
}
// app.cpp
...
val v = val::global("json_parse")(some_str);

Build:

emcc app.cpp -o app.js --bind --extern-pre-js extern_pre.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM