1

我正在使用 Ranorex 一个基于 c# 的测试自动化工具,并且有一个问题:异常处理和重新抛出异常。我对 c# 编程还很陌生,所以请多多包涵!考虑以下代码:

子类/方法..

try
{
    do something;
    'unhandled exception on line 150'
}

catch (exception)
{
    throw;
}

父类/方法

try
{
     childmethod();
}

catch (exception ex)
{
    report.info("Info",ex.Stacktrace);
}

我想做的是在子类/方法中但在父类异常处理程序中报告发生异常的行号。这样,在每个子类/方法中,我们可以将异常重新抛出(抛出)回主类/方法(即 Ranorex 术语中的测试用例)。在父异常处理程序中,我们还有其他事情要做,例如报告系统详细信息、关闭应用程序和测试失败。我们只想在一个地方执行此操作,因此放在顶级课程中。但是,使用上面的代码,stracktrace 会显示重新抛出的子异常处理程序中的行号以及调用子方法的行号。如果我们可以从堆栈跟踪中提取一些格式化的东西,这也会很有用

Class = 'class name' & Method = 'method name' & Line Num = 'line num' 

而不是整个堆栈跟踪消息。

我们正在使用 .net v4.0

谢谢你的帮助。

堆栈跟踪:

The stacktrace information is: at System.Data.DataRow.GetDataColumn(String columnName)
at System.Data.DataRow.get_Item(String columnName)
at ABCTest.SUD.Plat.NewFU.NewFUUserCode.MainMethod(String testDataInstanceId) in c:\Ranorex Local Code\ABCTest\ABCTest\SUD\Plat\NewFU\NewFUUserCode.cs:line 103
at ABCTest.SUD.Plat.NewFU.NewFUUserCode.MainMethod(String testDataInstanceId) in c:\Ranorex Local Code\ABCTest\ABCTest\SUD\Plat\NewFU\NewFireFUUserCode.cs:line 130
at ABCTest.Tests.ManageFAndS.ManACA_IO_One.MainMethod() in c:\Ranorex Local Code\ABCTest\ABCTest\Tests\ManageFAndS\ManACA_IO_One.cs:line 59
4

1 回答 1

0

这里http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx有一个解决方案。我不确定我是否会在我的代码中使用它,因为它基于一个未记录的方法(但它仍然适用于 .NET 4.0)

private static void PreserveStackTrace(Exception exception)
{
    MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
        BindingFlags.Instance | BindingFlags.NonPublic);
    preserveStackTrace.Invoke(exception, null);
}

static void MethodChild()
{
    try
    {
        throw new ArgumentException();
    }
    catch (Exception ex)
    {
        // Very important! Do it before rethrowing
        PreserveStackTrace(ex);
        throw;
    }
}

这个关于 SO 的回复解释了这个问题:你不能有两个相同方法的堆栈帧。一种方法 = 一个堆栈帧。

要获取有关引发异常的位置的信息,您可以使用StackTrace类:

StackTrace st = new StackTrace(ex, true);
StackFrame frame = st.GetFrame(0);
MethodBase method = frame.GetMethod();

// What you want!
string methodName = method.Name;
string className = method.DeclaringType.FullName;
int lineNumber = frame.GetFileLineNumber();

将异常传递给构造函数并true作为第二个参数。

于 2013-08-07T08:50:34.067 回答