clearscript

ClearScript: how to get object values


I have ClearScript that can do either

error = "value is invalid";

or

error = [
        {
            language: 'en',
            message: "value is invalid"
        },
        {
            language: 'fr',
            message: "valeur incorrecte"
        }
    ];

How, in C# can I get the values in the array?

And, to get either one case or the other I don't have a choice to do a try/catch, do I?


Solution

  • If your script sets up a global variable named error as shown above, you can process it like this:

    dynamic error = engine.Script.error;
    var message = error as string;
    if (message != null) {
        Console.WriteLine(message);
    }
    else if (error is ScriptObject) {
        if (error.constructor.name == "Array") {
            for (var i = 0; i < error.length; ++i) {
                Console.WriteLine("({0}) {1}", error[i].language, error[i].message);
            }
        }
        else {
            // handle other error types
        }
    }