Search code examples
v8embedded-v8

Fallback callback when calling unavailable function


Is it possible to set a fallback callback which is called when the user wants to call a function which does not exists? E.g.

my_object.ThisFunctionDoesNotExists(2, 4);

Now I want that a function is getting called where the first parameter is the name and a stack (or something like that) with the arguments passed. To clarify, the fallback callback should be a C++ function.


Solution

  • Assuming your question is about embedded V8 engine which is inferred from tags, you can use harmony Proxies feature:

    var A = Proxy.create({
        get: function (proxy, name) {
            return function (param) {
                console.log(name, param);
            }
        }
    });
    
    A.hello('world');  // hello world
    

    Use --harmony_proxies param to enable this feature. From C++ code:

    static const char v8_flags[] = "--harmony_proxies";
    v8::V8::SetFlagsFromString(v8_flags, sizeof(v8_flags) - 1);
    

    Other way:

    There is a method on v8::ObjectTemplate called SetNamedPropertyHandler so you can intercept property access. For example:

    void GetterCallback(v8::Local<v8::String> property,
        const v8::PropertyCallbackInfo<v8::Value>& info)
    {
        // This will be called on property read
        // You can return function here to call it
    }
    ...
    
    object_template->SetNamedPropertyHandler(GetterCallback);