How to use ErrorListener for IronRuby

北战南征 提交于 2019-12-02 02:21:51

What you're trying to do seems to not actually work. Not sure if it's a bug or not, though.

To workaround it, just execute the code inside a try/catch block and look for MissingMethodExecption. Pay attention that this also will not help if the syntax error is inside a method since IronRuby (or any other dynamic language) doesn't do anything with "nested" code until it actually executes it.

So in general, I think you won't get a lot of value from what you're trying to do.

The try/catch code sample:

ScriptEngine engine = null;
engine = Ruby.CreateEngine(x => { x.ExceptionDetail = true; });         

ScriptSource sc = engine.CreateScriptSourceFromFile("MainForm.rb");
ErrorListener errLis = new MyErrorListener();
sc.Compile(errLis);

try
{
    dynamic d = sc.Execute();
}
catch (MissingMethodException e)
{
    Console.WriteLine("Syntax error!");
}
Sanjay

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!