Skip to content
Jing Lu edited this page Jun 17, 2013 · 34 revisions

Error handling in .NET

Get errors from script execution

Get errors at compile-time

ReoScript support to pre-interpret the script in text and converts it into a syntax-tree in memory (like compiling). During this operation, all the syntax errors can be detected and handled.

There is three ways to get errors at compiling-time.

  1. Catch compiling exception

    When the syntax-error is detected, ReoScript throws the ReoScriptCompilingException and terminates the compiling operation instantly.

     ScriptRunningMachine srm = new ScriptRunningMachine();
     	
     CompiledScript cs = null;
     try
     {
         cs = srm.Compile("console.log('a);");              // string end without '
     }
     catch (ReoScriptCompilingException ex)
     {
         MessageBox.Show(ex.Message);
     }
    

The message displayed as below:

    syntax error at char 16 on line 1, unexpected token <EOF>
  1. Try compiling the whole script, and get an error list after compiling is finished

    By passing the second parameter as true to srm.Compile method indicates ReoScript to put any detected syntax-error into an error list.

     cs = srm.Compile(@"
     var hello = function() {
         console.log('hello');    
     }                            /* error: missing ; */
    
     hello();
    
     function fun1() {
         return function() {        /* error: missing } */
     };
    
     fun1();
     ", true);
    
     foreach (ErrorObject e in cs.CompilingErrors)
     {
         Console.WriteLine(e.Message);
     }
    
  2. Get an error list after pre-interpret is finished

    ScriptRunningMachine srm = new ScriptRunningMachine(); CompiledScript cs = srm.Compile("console.log('a')");

    foreach(ErrorObject e in cs.ErrorList) { }

Get errors at run-time

Get errors from Console Runner

Error Handling in script

Standard ECMAScript try/catch/finally/throw are supported by ReoScript.

Catch Error

Any errors could be caught using try catch syntax:

try {
  // calling non-existent function causes a run-time error
  undefinedfunc();
} catch(e) {
  // e is instance of Error function
  alert(e.message);
}

Finally

Does not matter what result about try block, the finally block always be executed.

allocMemory();

try {
  // do something and error here
  undefinedfunc();
} catch(e) {
  console.log(e);
} finally {
  releaseMemory();
}

Custom Error

You may throw a customize error with message.

try {
  if (true) {
    throw new Error('error anyway');
  }
} catch(e) {
  alert(e.message)     // 'error anyway'
}

Nested Try Catch

Errors could be thrown again, or with new one instead of old.

try {
  try {
    throw 'inner error';
  } catch(e) {
    if(e == 'inner error') {
      throw 'outer error';
    }
  }
} catch(e) {
  // e is 'outer error'
}

Clone this wiki locally