Home > database >  Emscripten: How to catch JS exception?
Emscripten: How to catch JS exception?

Time:02-01

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

CodePudding user response:

Based on documentation:

By default, exception catching is disabled in Emscripten.

You have to enable it with the -fexceptions argument.

CodePudding user response:

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
  •  Tags:  
  • Related