Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

异常处理

本节介绍如何处理QuickJS异常。

何时发生异常

  • 返回JSValue的函数,使用JS_IsException判断是否是异常
  • 返回整数值的函数,如果小于0,则发生异常。

发生异常时得到异常

典型的方式如下:

void LogException(JSContext* ctx) {
    JSValue exception_val = JS_GetException(ctx);
    bool is_error = JS_IsError(ctx, exception_val);

    // convert quickjs exception to string
    const char* str = JS_ToCString(ctx, exception_val);
    if (str) {
        std::cerr << str << std::endl;
        // don't forget to free
        JS_FreeCString(ctx, str);
    }

    if (is_error) {
        // get stack info
        val = JS_GetPropertyStr(ctx, exception_val, "stack");
        if (!JS_IsUndefined(val)) {
            const char* stack_info = JS_ToCString(ctx, val);
            std::cerr << "stack: " << stack_info << std::endl;
            JS_FreeCString(ctx, stack_info);
        }
        JS_FreeValue(ctx, val);
    }

    JS_FreeValue(ctx, exception_val);
}

当有异常抛出时,异常会被记录在JSContext中。使用JS_GetException拿出,转换成字符串输出即可。如果有堆栈信息也可以一并输出。

在有异常时即可调用:

JSValue result = JS_Eval(ctx, content.c_str(), content.size(), nullptr,
                         JS_EVAL_FLAG_STRICT | flags);

if (JS_IsException(result)) {
    LogException(ctx);
}