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!
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
undefinedfor 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!