Search code examples
javascriptc++ctry-catchduktape

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


Solution

  • 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.