2011-04-14 110 views
2

是否可以确定PostError中的调用方法名称“吃披萨”? 我想我可以通过“EatPizza”作为参数之一,但每次方法名称更改时都需要更改(不必要的维护)。但之后,我甚至无法在“EatPizza”的上下文中找到方法名称“EatPizza”(使用stacktrace,getframe,getmethod)。获取方法被调用的方法?

public void EatPizza(Pizza p){ 
    if(p==null){ //A arbitrary made up error 
     Utilities.PostError(); 
    } 
    else{ 
     p.Slices -= 1; 
    } 
} 

... 

public void PostError(){ 
    //Basically posting to database the name of the method 
    //Tried this, didn't work: (new StackTrace(true)).GetFrame(5).GetMethod().Name 
    //Is it possible to determine the calling method name "Eat Pizza" in this context? 
} 

当我尝试不同的值(0至StackTrace.FrameCount-1)StackTrace.GetFrame,我得到下面的值,如果我只是想 “EatPizza”:

.ctor 
ThreadStart 
Main 
_nExecuteAssembly 
RunUsersAssemblyDebugInZone 
+0

“没有工作”以什么方式? – 2011-04-14 17:51:26

+0

我添加了一个附录 – sooprise 2011-04-14 17:53:13

+0

你知道,抛出一个异常会得到堆栈跟踪,并且是推荐的处理错误的方法。你有没有这样做的理由?如果需要,您可以在catch块中调用PostError。 – driis 2011-04-14 17:53:33

回答

4

你是上正确的轨道与创建StackTrace对象,但你似乎误解了GetFrame的论点。帧从最底部帧编号,所以:

  • GetFrame(0)将返回PostError
  • GetFrame(1)将返回PostError
来电

所以才尝试这个办法:

var trace = new StackTrace(true); 
WriteToDB(trace.GetFrame(1).GetMethod().Name); 

就我个人而言,我宁愿得到整个堆栈跟踪而不是ju ST来电,所以我应该这样做:

var trace = new StackTrace(true); 
WriteToDB(trace.ToString()); 
+1

+1如果你打算用部分追踪记录错误,为什么不包括整个事情并获得拥有“全局图”的优势? – 2011-04-14 18:00:07

+0

+1,是的,这一切都合情合理。堆栈跟踪包含足够的信息用于我的错误日志记录目的,谢谢! – sooprise 2011-04-14 18:03:08

2

是否有可能确定调用方法名PostError“吃披萨”?我想我可以通过“EatPizza”作为参数之一,但每次方法名称改变时都需要更改(不必要的维护)。

在所有可能出错的方法中调用PostError也是“不必要的维护”。这也会使程序的执行流程变得复杂,因为您必须检查整个地方的错误,而高级进程将不得不检查低级进程是否成功完成。

最好使用由CLR和C#提供的异常处理结构。

错误发生的确切位置存储在异常的StackTrace属性中。

pubic void BigDinnerEatingProcess() 
{ 
    try 
    { 
     WhateverHappensAtTheTopLevel(); 
    } 
    catch (PizzaNotDeliveredException ex) 
    { 
     Utilities.PostError(ex); 
     MessageBox.Show("Dinner was not eaten. Please make sure the pizza is delivered."); 
    } 
} 

public void EatPizza(Pizza p) 
{ 
    if (p == null) 
     throw new PizzaNotDeliveredException(); 
    p.RemoveOneSlice(); 
} 

private void PostError(Exception ex) 
{ 
    string errorLocation = ex.StackTrace; 
    //... 
} 
+0

+1不必要的复杂。 @sooprise如果你决定重构你的日志记录方法,那么'StackTrace.GetFrame'现在变成了2层而不是1层?然后,您必须在整个代码中手动调整+1帧。 – bottlenecked 2011-04-14 18:11:48