[英]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. Emscripten 'val.h' API 允许调用 JS 对象的方法,但是 C++ try-catch 不会捕获 JS 异常。 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. JS 异常使“测试” function 停止并且没有
ok
,没有failed
,没有ret
打印出来。 How to catch that JS exception thrown by JSON.parse
?如何捕捉
JSON.parse
抛出的 JS 异常?
There's 1 issue here but it's still open: https://github.com/emscripten-core/emscripten/issues/11496这里有 1 个问题,但它仍然存在: https://github.com/emscripten-core/emscripten/issues/11496
Based on documentation :基于文档:
By default, exception catching is disabled in Emscripten.
默认情况下,Emscripten 中禁用异常捕获。
You have to enable it with the -fexceptions
argument.您必须使用
-fexceptions
参数启用它。
Emscripten doesn't seem to be able to catch JS exceptions in C++ yet. Emscripten 似乎还不能在 C++ 中捕获 JS 异常。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.