This project has moved and is read-only. For the latest updates, please go here.

Exception propagation from C# to Javascript

Jun 28, 2016 at 2:34 PM
Edited Jun 28, 2016 at 3:27 PM

I have a number of C# host objects added into the engine.
In case of exception within C#, the exception caught in the javascript has message as "Exception has been thrown by the target of an invocation" and type as object. Here is the sample code:
loginResponse = httpclient.Post(url,payload);
var type = typeof err;
httpclient and Log are my host objects here.

I tried adding the expected exception type as hosttype but still its the same.

Is there any better way to handle this ?
I need to know the actual type or message. Looks like the whole exception object is getting lost ?
Jun 28, 2016 at 2:57 PM
Hello maicalal,

Which JavaScript engine are you using (V8 or JScript)?

Jun 28, 2016 at 3:22 PM
Jun 28, 2016 at 7:56 PM
Hi again,

When you use V8, ClearScript marshals host exceptions to script code. In the above, the host exception should be accessible via err.hostException. Note that this is likely to be an instance of TargetInvocationException, so you might want to use err.hostException.GetBaseException() to access the "root" exception (see here).

Another possibility (and one that works with all script engines) is to use ClearScript's HostFunctions.tryCatch.

Good luck!
Jun 29, 2016 at 7:13 AM
Edited Jun 29, 2016 at 8:00 AM

I tried err.hostException, but this came as null.

I then added HostFunctions as host object and tried your next suggestion. But looks like HostFunctions does not have tryCatch().
My Clearscript version is :

I tried Like below:
-------adding HostFunctions to engine----------
engine.AddHostObject("host", new HostFunctions());

In javascript

var succeeded = host.tryCatch(
    function() {
        loginResponse = httpclient.Post(url,payload);
    function(exception) {
        hostException = exception;
        return true;
if (succeeded) {    
else {
    Log.Error('err msg...' + hostException.Message);
    Log.Error('err type...' + hostException.GetBaseException().ToString());

This fails saying "Microsoft.ClearScript.ScriptEngineException: TypeError: Object #<HostObject> has no method 'tryCatch'"

do I need to upgrade or I got you wrong?
Jun 29, 2016 at 10:33 AM

I guess will need to upgrade, came to know from your responses @
related post...

Thanks for your suggestions :)...
Jun 29, 2016 at 2:24 PM
Hi maicalal,

Yes, unfortunately you'll have to upgrade to get the newer exception handling features.