在C#中捕获Ironpython异常

foo*_*bar 6 ironpython exception

我在C#中嵌入了IronPython 2.0.在IronPython中,我用以下内容定义了自己的异常:

def foobarException(Exception):
    pass 
Run Code Online (Sandbox Code Playgroud)

并将其提升到某个地方:

raise foobarException( "This is the Exception Message" )
Run Code Online (Sandbox Code Playgroud)

现在在C#中,我有:

try
{
   callIronPython();
}
catch (Exception e)
{
   // How can I determine the name (foobarException) of the Exception
   // that is thrown from IronPython?   
   // With e.Message, I get "This is the Exception Message"
}
Run Code Online (Sandbox Code Playgroud)

fuz*_*man 16

当您从C#捕获IronPython异常时,可以使用Python引擎来设置回溯的格式:

catch (Exception e)
{
    ExceptionOperations eo = _engine.GetService<ExceptionOperations>(); 
    string error = eo.FormatException(e); 
    Console.WriteLine(error);
}
Run Code Online (Sandbox Code Playgroud)

您可以从回溯中提取异常名称.否则,您将不得不调用IronPython托管API直接从异常实例中检索信息.engine.Operations有这些交互的有用方法.


foo*_*bar 1

我最终的解决方案是:

我有一个 C# 结果类,它被传递给我的ironpython 代码。在 Ironpython 中,我用所有计算值填充结果类。我刚刚向此类添加了一个成员变量 IronPythonExceptionName。现在我只是在 IronPython 中进行了简单的尝试:

try: 
    complicatedIronPythonFunction()
except Exception, inst:
    result.IronPythonExceptionName = inst.__class__.__name__
    raise inst
Run Code Online (Sandbox Code Playgroud)