Clearscript: How to throw exception when get a non-exists property in ExpandoObject

Created on 25 Nov 2019  路  3Comments  路  Source: microsoft/ClearScript

See the code below:

        public static void Main(string[] args)
        {
            using (V8ScriptEngine engine = new V8ScriptEngine())
            {
                dynamic data = new ExpandoObject();                

                engine.AddRestrictedHostObject("doc", data);

                object result = engine.Evaluate("doc.aaa");


                Console.WriteLine(result.GetType());
            }

            Console.ReadLine();
        }

Now we can get Microsoft.ClearScript.Undefined in output window. Is it possible to throw an exception say "The aaa is not defined in doc." ?

Thank you!

question

All 3 comments

Hi @arthurshayne

Returning undefined for a nonexistent property is standard JavaScript behavior, and ClearScript can't always override it, particularly with JScript.

However, if you're using V8, one way to override most behaviors is by wrapping a proxy around your object:

C# dynamic data = new ExpandoObject(); engine.Script.doc = ((dynamic)engine.Evaluate(@"(function (target) { return new Proxy(target, { get: function (target, prop) { if (Reflect.has(target, prop)) { return Reflect.get(target, prop); } throw new Error('Property not found'); } }); })"))(data);

Good luck!

Hi @arthurshayne

Returning undefined for a nonexistent property is standard JavaScript behavior, and ClearScript can't always override it, particularly with JScript.

However, if you're using V8, one way to override most behaviors is by wrapping a proxy around your object:

dynamic data = new ExpandoObject();
engine.Script.doc = ((dynamic)engine.Evaluate(@"(function (target) {
    return new Proxy(target, {
        get: function (target, prop) {
            if (Reflect.has(target, prop)) {
                return Reflect.get(target, prop);
            }
            throw new Error('Property not found');
        }
    });
})"))(data);

Good luck!

That works for me! Great Thanks!

Please reopen this issue if you have additional questions about this topic. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JohnLudlow picture JohnLudlow  路  4Comments

JohnLudlow picture JohnLudlow  路  4Comments

JohnLudlow picture JohnLudlow  路  4Comments

AllNamesRTaken picture AllNamesRTaken  路  7Comments

flat-eric147 picture flat-eric147  路  5Comments