Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duktape - catch errors in C

I just started using Duktape in my C++ framework today, and I've read the entire api without being able to understand how do i catch errors. I found some clues about an error object that is put on the stack However, every time there is an error (like an invalid javascript syntax for example), everything goes crazy and i get a SEGFAULT.

I'm currently evaluating some js lines using the duk_eval function

Here's my lines of code :

duk_push_string(ctx,"pouet");
duk_eval(ctx);

ctx is the base context that you provide when creating duktape heap

Using try-catch doesn't catch anything

Any idea?

Thanks in advance

like image 414
Lordrem Avatar asked Feb 17 '26 03:02

Lordrem


1 Answers

You can "catch" errors during execution of JavaScript code by using the protected variant of duk_eval which is duk_peval:

duk_push_string(ctx, "syntax error=");
if (duk_peval(ctx) != 0) {
    printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    printf("result is: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);  /* pop result */

Do not confuse exceptions triggered by JavaScript code with C++ exceptions: Duktape is implemented in C and does not know about features provided by the C++ standard library. When using the non-protected duk_eval function variant the application is terminated by default. You can change that by assigning an own fatal handler, which in your case could throw a C++ exception if desired.

like image 125
blerontin Avatar answered Feb 19 '26 16:02

blerontin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!