I have a C# program to execute an IronRuby script. But before doing that, I\'d like to compile the file first to see if there is any errors. But it seems the ErrorListener does
I researched on this problem finally found the solution that is first write your ErrorListener Class in following Manger.
public class IronRubyErrors : ErrorListener
{
public string Message { get; set; }
public int ErrorCode { get; set; }
public Severity sev { get; set; }
public SourceSpan Span { get; set; }
public override void ErrorReported(ScriptSource source, string message, Microsoft.Scripting.SourceSpan span, int errorCode, Microsoft.Scripting.Severity severity)
{
Message = message;
ErrorCode = errorCode;
sev = severity;
Span = span;
}
}
then
var rubyEngine = Ruby.CreateEngine();
ScriptSource src = rubyEngine.CreateScriptSourceFromFile("test.rb");
IronRubyErrors error = new IronRubyErrors();
src.Compile(error);
if (error.ErrorCode != 0)
{
MessageBox.Show(string.Format("Discription {0} \r\nError at Line No.{1} and Column No{2}", error.Message, error.span.Start.Line, error.span.Start.Column));
}
try
{
if (error.ErrorCode == 0)
{
var res = src.Execute();
}
}
catch (MissingMethodException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Because Ironruby is DLR therefore it compiles On RunTime if characters which are not the keyword of IronRuby like (~ ,` , ^ and so On) OR you have created any Syntax Error other then Error will capture on Compile Method of ScriptSource and the object of ErrorListener Class will be filled and we will find ErrorCode etc. if you have used a Method which is not defined in Ruby Library for example you have typed the method for Number Conversion like this
@abc.to_
which is not correct then it will be caught in MissingMethodException Block
Correct method is
@abc.to_f
and if you got Error Other then these (like Divide by Zero Exception)then that will be caught in Exception Block