Avg. Rating 3.5

Problem

I need to know method sequence that invoked some instructions.

Solution

I will use Error.getStackTrace() method

Detailed explanation

Error class has very useful method Error.getStackTrace() that returns you a stack of called functions that caused to creation error instance.
Usually I am using this method in two cases. First is just a trace in some places (without application pause if it is running in a debug mode):

trace((new Error()).getStackTrace());


I am using a simple wrapper class for this one:

package aw.utils{
    public class DebugUtils extends Object{
        static public function traceStack(...args):void{
            args.push(getStack());
            trace.apply(null, args);
        }
        static public function getStack():String{
            var stack:String = (new Error('')).getStackTrace();
            var index:int = stack.lastIndexOf('DebugUtils');
            if(index>=0){
                index = stack.indexOf('\n', index);
                stack = stack.substr(index);
            }
            return stack;
        }
    }
}


Second use case is a spying on instances of some objects. For example, you need to know where and how exactly instance was created, just put error into a class constructor:

protected var _debugInfo:Error;
public function SomeClassConstructor(debug:Boolean=true):void{
    super();
    _debugInfo = debug ? new Error() : null;
}



And you can add some methods to format and/or trace your info:

public function getConstructionStackTrace():String{
    var stack:String = '';
    if(this._debugInfo){
        stack = this._debugInfo.getStackTrace();
        var stackList:Array = stack.split('\n');
        stackList[0] = 'SomeClass construction stack trace:';
        stack = stackList.join('\n');
    }
    return stack;
}

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes