How to get filename and line number of where a function is called?
Question: When working in Python I always have this simple utility function which
returns the file name and line number from where the function is called:

    
    
    from inspect import getframeinfo, stack
    def d():
        """ d stands for Debug. It returns the file name and line number from where this function is called."""
        caller = getframeinfo(stack()[1][0])
        return "%s:%d -" % (caller.filename, caller.lineno)
    

So in my code I simply put a couple debug lines like this to see how far we
get before some error occurs:

    
    
    print d()
    # Some buggy code here
    print d()
    # More buggy code here
    print d(), 'here is the result of some var: ', someVar
    

This works really well for me because it really helps debugging quickly.

I'm now looking for the equivalent in Javascript. I was searching around but I
can't find anything useful (maybe I'm looking for the wrong words?).

Does anybody know how I can create a Javascript function which outputs the
file name and line number from where the function is called? All tips are
welcome!


Answer: The only way I've found to get anything relating to line numbers is to trap
the `window.onerror` function, and when there's an error that will get passed
the error message, the file URL and the line number:

    
    
    window.onerror = function(msg, url, line) {
        alert(msg + "\n" + url + ":" + line);
    };
    

This works for me on Chrome - I don't know about other browsers.

