2009-02-26 9 views
362

Se lancio personalmente un'eccezione Javascript (ad esempio, throw "AArrggg"), come posso ottenere la traccia dello stack (in Firebug o in altro modo)? In questo momento ho appena ricevuto il messaggio.Come posso ottenere una traccia dello stack Javascript quando lancio un'eccezione?

modificare: Come molte persone al di sotto hanno inviato, è possibile ottenere una traccia dello stack per un'eccezione JavaScript ma voglio ottenere una traccia dello stack per miei eccezioni. Per esempio:

function foo() { 
    bar(2); 
} 
function bar(n) { 
    if (n < 2) 
     throw "Oh no! 'n' is too small!" 
    bar(n-1); 
} 

Quando foo si chiama, voglio ottenere una traccia dello stack che comprende le chiamate verso foo, bar, bar.

+0

Basta google per la traccia dello stack javascript. Riceverai la tua risposta! Eccone uno particolarmente interessante: http://helephant.com/2007/05/diy-javascript-stack-trace/ –

+1

possibile duplicato di [trace di eccezioni JavaScript] (http://stackoverflow.com/questions/147891/javascript- exception-stack-trace) – ripper234

+0

Bug è ancora aperto su Firebug bug tracker dal 2008: http://code.google.com/p/fbug/issues/detail?id=1260 - lo star! –

risposta

503

Una versione modificata di this snippet può in qualche modo aiutare:

function stacktrace() { 
    function st2(f) { 
    return !f ? [] : 
     st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']); 
    } 
    return st2(arguments.callee.caller); 
} 


EDIT (2017):

in tutti i browser moderni si può semplicemente chiamare: console.trace();(MDN Reference)

EDIT:

Una soluzione migliore (e più semplice), come ha sottolineato nel commento alla domanda iniziale è quello di utilizzare la proprietà stack di un oggetto Error in questo modo:

function stackTrace() { 
    var err = new Error(); 
    return err.stack; 
} 

Questo genererà un output simile this:

[email protected]://localhost:49573/assets/js/scripts.js:44 
[email protected]://localhost:49573/assets/js/scripts.js:9 
[email protected]://localhost:49573/:462 
x.Callbacks/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:4 
x.Callbacks/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:4 
[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:6 
.send/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:6 

Assegnare il nome della funzione chiamante con l'URL, la sua funzione di chiamata e così via.

+0

Questo sembra essere il più promettente finora ... Creare un 'Eccezione', quindi chiamare un'eccezione sarebbe: lanciare Eccezione ('messaggio'), dove la funzione Eccezione potrebbe capire cosa c'è in pila. –

+0

Bene, bene, poiché questa è la cosa più vicina a una risposta corretta, lo accetterò. –

+10

Non sono sicuro del motivo per cui questo non viene più votato - le altre risposte non hanno funzionato bene per me. BTW, assicurati di non trattare gli argomenti come una matrice (snippet aggiornato qui: https://gist.github.com/965603) – ripper234

10

Non penso che ci sia qualcosa di costruito che tu possa usare, ma ho trovato molti esempi di persone che si muovono da sole.

+0

Ah, grazie - il primo collegamento sembra non funzionare (anche se la mancanza di supporto per la ricorsione potrebbe renderlo impraticabile). –

+0

Sì, non ho visto nessuno che supportasse la ricorsione a prima vista. Sarò curioso di vedere se c'è una buona soluzione a questo. –

+1

Penso che il secondo link dovrebbe supportare la ricorsione per Firefox e Opera perché utilizza la traccia dello stack degli errori invece di crearne uno manualmente utilizzando la variabile arguments. Mi piacerebbe sapere se trovi una soluzione cross browser per il problema della ricorsione (il primo articolo è mio). :) – Helephant

26

Se si dispone di Firebug, c'è una pausa su tutta l'opzione errori nella scheda script. Una volta che lo script ha colpito il punto di interruzione, si può guardare alla finestra stack di Firebug:

screenshot

+5

Hrm, non sembra funzionare. Mi arresta in un debugger sugli errori generati da Javascript (ad es. Errori di variabile non definiti), ma quando lancio le mie eccezioni non ottengo altro che il messaggio "Eccezione non rilevata". –

0

E 'più facile per ottenere una traccia dello stack su Firefox di quanto lo sia su IE ma fondamentalmente qui è quello che si vuole fare:

Avvolgere il pezzo "problematico" di codice in un blocco try/catch:

try { 
    // some code that doesn't work 
    var t = null; 
    var n = t.not_a_value; 
} 
    catch(e) { 
} 

Se si esamina il contenuto del "errore" oggetto che contiene i seguenti campi:

e.fileName: il file di origine/pagina in cui il problema è venuto da e.lineNumber: il numero di riga nel file/pagina in cui è emerso il problema e.message: un messaggio semplice che descrive il tipo di errore verificatosi e.name: il tipo di errore che si è verificato, nell'esempio precedente dovrebbe essere 'TypeError' e.stack: contiene la traccia dello stack che ha causato l'eccezione

Spero che questo ti aiuti.

+1

Sbagliato. Sta cercando di cogliere le Sue eccezioni. Se lancia "asdfg", otterrà oggetto stringa, non un oggetto eccezione. Non sta cercando di intercettare le eccezioni built-in. –

7

È possibile accedere alle proprietà stack (stacktrace in Opera) di un'istanza Error anche se è stata lanciata. La cosa è, è necessario assicurarsi di utilizzare throw new Error(string) (non dimenticate il nuova invece di throw string

Esempio:.

try { 
    0++; 
} catch (e) { 
    var myStackTrace = e.stack || e.stacktrace || ""; 
} 
+0

stacktrace non funziona in Opera. Non riesco nemmeno a trovare qualcosa al riguardo. – NVI

+0

@NV: Sembra che lo stacktrace non sia sugli errori creati dall'utente, quindi dovresti farlo invece: prova {0 ++} catch (e) {myStackTrace = e.stack || e.stacktrace} –

145

Nota che il cromo/cromo (altri browser utilizzando V8), e anche Firefox si dispone di una comoda interfaccia per ottenere uno stacktrace attraverso una pila proprietà su Errore oggetti.

try { 
    // Code throwing an exception 
} catch(e) { 
    console.log(e.stack); 
} 

Si applica per le eccezioni di base e per quelle che si lanciano. (Considerato che usi la classe Error, che comunque è una buona pratica).

Vedi dettagli su V8 documentation

+12

Firefox supporta anche la proprietà '.stack'. – kennytm

+2

Vorrei poter sopravvivere 100 volte! Grazie Jocelyn. È stato davvero molto utile usare – safrazik

+0

per 'console.error (e.stack);' quindi sembra un messaggio di eccezione predefinito –

6

un modo per ottenere una traccia del reale stack su Firebug è quello di creare un vero e proprio errore come si chiama una funzione non definita:

function foo(b){ 
    if (typeof b !== 'string'){ 
    // undefined Error type to get the call stack 
    throw new ChuckNorrisError("Chuck Norris catches you."); 
    } 
} 

function bar(a){ 
    foo(a); 
} 

foo(123); 

Oppure utilizzare console.error() seguito da una dichiarazione throw poiché console.error() mostra la traccia dello stack.

+0

console.error non mostra lo stack in safari ... – Sebas

3

In Google Chrome (versione 19.0 e successive), il semplice lancio di un'eccezione funziona perfettamente. Per esempio:

/* file: code.js, line numbers shown */ 

188: function fa() { 
189: console.log('executing fa...'); 
190: fb(); 
191: } 
192: 
193: function fb() { 
194: console.log('executing fb...'); 
195: fc() 
196: } 
197: 
198: function fc() { 
199: console.log('executing fc...'); 
200: throw 'error in fc...' 
201: } 
202: 
203: fa(); 

mostrerà l'analisi dello stack in uscita della console del browser:

executing fa...       code.js:189 
executing fb...       code.js:194 
executing fc...       cdoe.js:199 
/* this is your stack trace */ 
Uncaught error in fc...     code.js:200 
    fc         code.js:200 
    fb         code.js:195 
    fa         code.js:190 
    (anonymous function)    code.js:203 

Spero che questo aiuto.

66

In Firefox sembra che non sia necessario lanciare l'eccezione. E 'sufficiente fare

e = new Error(); 
console.log(e.stack); 
+0

Funziona in app mobili (create usando JQM) pure. –

+0

Funziona anche in Chromium (versione 43). –

8

Una buona (e semplice) soluzione come sottolineato nei commenti sulla domanda iniziale è quello di utilizzare la proprietà stack di un oggetto Error in questo modo:

function stackTrace() { 
    var err = new Error(); 
    return err.stack; 
} 

Questa volontà uscita generare in questo modo:

[email protected]://localhost:49573/assets/js/scripts.js:44 
[email protected]://localhost:49573/assets/js/scripts.js:9 
[email protected]://localhost:49573/:462 
x.Callbacks/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:4 
x.Callbacks/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:4 
[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:6 
.send/[email protected]://localhost:49573/assets/js/jquery-1.10.2.min.js:6 

Dare il nome della funzione di chiamata con l'URL e numero di riga, la sua funzione di chiamata, e così sopra.

Ho una soluzione davvero elaborata e carina che ho ideato per un progetto al momento sto lavorando e l'ho estratta e rielaborata un po 'per essere generalizzata. Eccolo:

(function(context){ 
    // Only global namespace. 
    var Console = { 
     //Settings 
     settings: { 
      debug: { 
       alwaysShowURL: false, 
       enabled: true, 
       showInfo: true 
      }, 
      stackTrace: { 
       enabled: true, 
       collapsed: true, 
       ignoreDebugFuncs: true, 
       spacing: false 
      } 
     } 
    }; 

    // String formatting prototype function. 
    if (!String.prototype.format) { 
     String.prototype.format = function() { 
      var s = this.toString(), 
       args = typeof arguments[0], 
       args = (("string" == args || "number" == args) ? arguments : arguments[0]); 
      if (!arguments.length) 
       return s; 
      for (arg in args) 
       s = s.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]); 
      return s; 
     } 
    } 

    // String repeating prototype function. 
    if (!String.prototype.times) { 
     String.prototype.times = function() { 
      var s = this.toString(), 
       tempStr = "", 
       times = arguments[0]; 
      if (!arguments.length) 
       return s; 
      for (var i = 0; i < times; i++) 
       tempStr += s; 
      return tempStr; 
     } 
    } 

    // Commonly used functions 
    Console.debug = function() { 
     if (Console.settings.debug.enabled) { 
      var args = ((typeof arguments !== 'undefined') ? Array.prototype.slice.call(arguments, 0) : []), 
       sUA = navigator.userAgent, 
       currentBrowser = { 
        firefox: /firefox/gi.test(sUA), 
        webkit: /webkit/gi.test(sUA), 
       }, 
       aLines = Console.stackTrace().split("\n"), 
       aCurrentLine, 
       iCurrIndex = ((currentBrowser.webkit) ? 3 : 2), 
       sCssBlack = "color:black;", 
       sCssFormat = "color:{0}; font-weight:bold;", 
       sLines = ""; 

      if (currentBrowser.firefox) 
       aCurrentLine = aLines[iCurrIndex].replace(/(.*):/, "[email protected]").split("@"); 
      else if (currentBrowser.webkit) 
       aCurrentLine = aLines[iCurrIndex].replace("at ", "").replace(")", "").replace(/(\()/gi, "@").replace(/(.*):(\d*):(\d*)/, "[email protected][email protected]$3").split("@"); 

      // Show info if the setting is true and there's no extra trace (would be kind of pointless). 
      if (Console.settings.debug.showInfo && !Console.settings.stackTrace.enabled) { 
       var sFunc = aCurrentLine[0].trim(), 
        sURL = aCurrentLine[1].trim(), 
        sURL = ((!Console.settings.debug.alwaysShowURL && context.location.href == sURL) ? "this page" : sURL), 
        sLine = aCurrentLine[2].trim(), 
        sCol; 

       if (currentBrowser.webkit) 
        sCol = aCurrentLine[3].trim(); 

       console.info("%cOn line %c{0}%c{1}%c{2}%c of %c{3}%c inside the %c{4}%c function:".format(sLine, ((currentBrowser.webkit) ? ", column " : ""), ((currentBrowser.webkit) ? sCol : ""), sURL, sFunc), 
          sCssBlack, sCssFormat.format("red"), 
          sCssBlack, sCssFormat.format("purple"), 
          sCssBlack, sCssFormat.format("green"), 
          sCssBlack, sCssFormat.format("blue"), 
          sCssBlack); 
      } 

      // If the setting permits, get rid of the two obvious debug functions (Console.debug and Console.stackTrace). 
      if (Console.settings.stackTrace.ignoreDebugFuncs) { 
       // In WebKit (Chrome at least), there's an extra line at the top that says "Error" so adjust for this. 
       if (currentBrowser.webkit) 
        aLines.shift(); 
       aLines.shift(); 
       aLines.shift(); 
      } 

      sLines = aLines.join(((Console.settings.stackTrace.spacing) ? "\n\n" : "\n")).trim(); 

      trace = typeof trace !== 'undefined' ? trace : true; 
      if (typeof console !== "undefined") { 
       for (var arg in args) 
        console.debug(args[arg]); 

       if (Console.settings.stackTrace.enabled) { 
        var sCss = "color:red; font-weight: bold;", 
         sTitle = "%c Stack Trace" + " ".times(70); 

        if (Console.settings.stackTrace.collapsed) 
         console.groupCollapsed(sTitle, sCss); 
        else 
         console.group(sTitle, sCss); 

        console.debug("%c" + sLines, "color: #666666; font-style: italic;"); 

        console.groupEnd(); 
       } 
      } 
     } 
    } 
    Console.stackTrace = function() { 
     var err = new Error(); 
     return err.stack; 
    } 

    context.Console = Console; 
})(window); 

Check it out sul GitHub (attualmente v1.2)! Puoi usarlo come Console.debug("Whatever"); e, a seconda delle impostazioni in Console, stampare l'output e una traccia dello stack (o semplicemente informazioni semplici/niente di più). Ecco un esempio:

Console.js

Assicurarsi di giocare con le impostazioni nell'oggetto Console! È possibile aggiungere una spaziatura tra le linee della traccia e disattivarla completamente. Qui è con Console.trace insieme a false:

No trace

È anche possibile disattivare il primo bit di informazioni indicato (impostato Console.settings.debug.showInfo-false) o disattivare il debug del tutto (impostare Console.settings.debug.enabled a false) in modo da non dover commenta di nuovo una dichiarazione di debug! Lasciali entrare e questo non farà nulla.

0

Tipo di ritardo alla festa, ma, ecco un'altra soluzione, che rileva automaticamente se arguments.callee è disponibile, e utilizza nuove Error() .stack se non. Testato in chrome, safari e firefox.

2 varianti - stackFN (n) fornisce il nome della funzione n lontano dal chiamante immediato e stackArray() fornisce un array, stackArray() [0] è il chiamante immediato.

Provalo ora a http://jsfiddle.net/qcP9y/6/

// returns the name of the function at caller-N 
// stackFN() = the immediate caller to stackFN 
// stackFN(0) = the immediate caller to stackFN 
// stackFN(1) = the caller to stackFN's caller 
// stackFN(2) = and so on 
// eg console.log(stackFN(),JSON.stringify(arguments),"called by",stackFN(1),"returns",retval); 
function stackFN(n) { 
    var r = n ? n : 0, f = arguments.callee,avail=typeof f === "function", 
     s2,s = avail ? false : new Error().stack; 
    if (s) { 
     var tl=function(x) { s = s.substr(s.indexOf(x) + x.length);}, 
     tr = function (x) {s = s.substr(0, s.indexOf(x) - x.length);}; 
     while (r-- >= 0) { 
      tl(")"); 
     } 
     tl(" at "); 
     tr("("); 
     return s; 
    } else { 
     if (!avail) return null; 
     s = "f = arguments.callee" 
     while (r>=0) { 
      s+=".caller"; 
      r--; 
     } 
     eval(s); 
     return f.toString().split("(")[0].trim().split(" ")[1]; 
    } 
} 
// same as stackFN() but returns an array so you can work iterate or whatever. 
function stackArray() { 
    var res=[],f = arguments.callee,avail=typeof f === "function", 
     s2,s = avail ? false : new Error().stack; 
    if (s) { 
     var tl=function(x) { s = s.substr(s.indexOf(x) + x.length);}, 
     tr = function (x) {s = s.substr(0, s.indexOf(x) - x.length);}; 
     while (s.indexOf(")")>=0) { 
      tl(")"); 
      s2= ""+s; 
      tl(" at "); 
      tr("("); 
      res.push(s); 
      s=""+s2; 
     } 
    } else { 
     if (!avail) return null; 
     s = "f = arguments.callee.caller" 
     eval(s); 
     while (f) { 
      res.push(f.toString().split("(")[0].trim().split(" ")[1]); 
      s+=".caller"; 
      eval(s); 
     } 
    } 
    return res; 
} 


function apple_makes_stuff() { 
    var retval = "iPhones"; 
    var stk = stackArray(); 

    console.log("function ",stk[0]+"() was called by",stk[1]+"()"); 
    console.log(stk); 
    console.log(stackFN(),JSON.stringify(arguments),"called by",stackFN(1),"returns",retval); 
    return retval; 
} 



function apple_makes(){ 
    return apple_makes_stuff("really nice stuff"); 
} 

function apple() { 
    return apple_makes(); 
} 

    apple(); 
0

ho dovuto indagare su una ricorsione infinita in smartgwt con IE11, così, al fine di indagare più a fondo, avevo bisogno di una traccia dello stack. Il problema era che non ero in grado di usare la console di sviluppo, perché la riproduzione era più difficile in quel modo.
Usare il seguente in un metodo javascript:

try{ null.toString(); } catch(e) { alert(e.stack); } 
+0

alert ((new Error()). stack); –

1

Si potrebbe usare questa libreria http://www.stacktracejs.com/.E 'molto buona

Dalla documentazione

You can also pass in your own Error to get a stacktrace not available in IE or Safari 5-

<script type="text/javascript" src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script> 
<script type="text/javascript"> 
    try { 
     // error producing code 
    } catch(e) { 
     var trace = printStackTrace({e: e}); 
     alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n')); 
     // do something else with error 
    } 
</script> 
+0

L'origine collegata 'https: // rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js' è una vecchia versione, la versione più recente stabile (corrispondente allo snippet di codice) è qui:' https: // raw .githubusercontent.com/stacktracejs/stacktrace.js/stable/stacktrace.js' –

4

Questo vi darà una traccia dello stack (come array di stringhe) per la moderna Chrome, Opera, Firefox e IE10 +

function getStackTrace() { 

    var stack; 

    try { 
    throw new Error(''); 
    } 
    catch (error) { 
    stack = error.stack || ''; 
    } 

    stack = stack.split('\n').map(function (line) { return line.trim(); }); 
    return stack.splice(stack[0] == 'Error' ? 2 : 1); 
} 

Usage:

console.log(getStackTrace().join('\n')); 

Esclude dallo stack la propria chiamata e il titolo "Errore" utilizzato da Chrome e Firefox (ma non da IE).

Non dovrebbe bloccarsi sui browser più vecchi, ma restituire semplicemente l'array vuoto. Se hai bisogno di più soluzioni universali, consulta stacktrace.js. La sua lista di browser supportati è davvero impressionante, ma a mio avviso è molto grande per quel piccolo compito che è destinato a: 37Kb di testo minificato comprese tutte le dipendenze.

5

Un aggiornamento alla risposta di Eugene: L'oggetto errore deve essere gettato in modo che IE (versioni specifiche?) Compili la proprietà stack. Il seguente dovrebbe funzionare meglio del suo esempio corrente e dovrebbe evitare di restituire undefined quando in IE.

function stackTrace() { 
    try { 
    var err = new Error(); 
    throw err; 
    } catch (err) { 
    return err.stack; 
    } 
} 

Nota 1: Questo genere di cose deve essere fatto solo durante il debug, e disattivata quando dal vivo, soprattutto se chiamato di frequente. Nota 2: Questo potrebbe non funzionare in tutti i browser, ma sembra funzionare in FF e IE 11, che si adattano perfettamente alle mie esigenze.

0

Wow - Non vedo una singola persona in 6 anni che suggerisca di controllare prima di vedere se stack è disponibile prima di utilizzarlo! La cosa peggiore che puoi fare in un gestore di errori è lanciare un errore a causa di chiamare qualcosa che non esiste.

Come altri hanno già detto, mentre il stack è quasi sicuro da utilizzare ora non è supportato in IE9 o versioni precedenti.

Registro gli errori imprevisti e una traccia di stack è piuttosto essenziale. Per il massimo supporto, per prima cosa controlla se esiste Error.prototype.stack ed è una funzione. Se è così allora è sicuro usare error.stack.

 window.onerror = function (message: string, filename?: string, line?: number, 
            col?: number, error?: Error) 
     { 
      // always wrap error handling in a try catch 
      try 
      { 
       // get the stack trace, and if not supported make our own the best we can 
       var msg = (typeof Error.prototype.stack == 'function') ? error.stack : 
          "NO-STACK " + filename + ' ' + line + ':' + col + ' + message; 

       // log errors here or whatever you're planning on doing 
       alert(msg); 
      } 
      catch (err) 
      { 

      } 
     }; 

Edit: Sembra che da quando stack è una proprietà e non un metodo si può tranquillamente chiamare anche su browser più vecchi. Sono ancora confuso perché ero abbastanza sicuro che il controllo difunzionasse per me in precedenza e ora non funziona, quindi non sono sicuro di cosa sta succedendo.

2
<script type="text/javascript" 
src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script> 
<script type="text/javascript"> 
    try { 
     // error producing code 
    } catch(e) { 
     var trace = printStackTrace({e: e}); 
     alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n')); 
     // do something else with error 
    } 
</script> 

questo script mostrerà l'errore

0

Utilizzando console.error(e.stack) Firefox mostra solo lo stacktrace in ceppi, Chrome mostra anche il messaggio. Questa può essere una brutta sorpresa se il messaggio contiene informazioni vitali. Registra sempre entrambi.

2

funzione:

function print_call_stack(err) { 
    var stack = err.stack; 
    console.error(stack); 
} 

caso d'uso:

 try{ 
     aaa.bbb;//error throw here 
    } 
    catch (err){ 
     print_call_stack(err); 
    } 
0
function stacktrace(){ 
    return (new Error()).stack.split('\n').reverse().slice(0,-2).reverse().join('\n'); 
} 
+0

Sebbene questo codice possa rispondere alla domanda, fornire un contesto aggiuntivo riguardo a come e/o perché risolve il problema migliorerebbe il valore a lungo termine della risposta. –

0

Ecco una risposta che offre prestazioni max (IE 6+) e la compatibilità max. Compatibile con IE 6!

function stacktrace(log_result) { 
 
    \t var trace_result; 
 
    // IE 6 through 9 compatibility 
 
    // this is NOT an all-around solution because 
 
    // the callee property of arguments is depredicated 
 
    /*@cc_on 
 
    \t // theese fancy conditinals make this code only run in IE 
 
    \t trace_result = (function st2(fTmp) { 
 
    \t \t // credit to Eugene for this part of the code 
 
    \t \t return !fTmp ? [] : 
 
    \t \t \t st2(fTmp.caller).concat([fTmp.toString().split('(')[0].substring(9) + '(' + fTmp.arguments.join(',') + ')']); 
 
    \t })(arguments.callee.caller); 
 
    \t if (log_result) // the ancient way to log to the console 
 
    \t \t Debug.write(trace_result); 
 
    \t return trace_result; 
 
    @*/ 
 
    \t console = console || Console; \t // just in case 
 
    \t if (!(console && console.trace) || !log_result){ 
 
    \t \t // for better performance in IE 10 
 
    \t \t var STerror=new Error(); 
 
    \t \t var unformated=(STerror.stack || STerror.stacktrace); 
 
    \t \t trace_result = "\u25BC console.trace" + unformated.substring(unformated.indexOf('\n',unformated.indexOf('\n'))); 
 
    \t } else { 
 
    \t \t // IE 11+ and everyone else compatibility 
 
    \t \t trace_result = console.trace(); 
 
    \t } 
 
    \t if (log_result) 
 
    \t \t console.log(trace_result); 
 
    \t 
 
    \t return trace_result; 
 
    } 
 
// test code 
 
(function testfunc(){ 
 
\t document.write("<pre>" + stacktrace(false) + "</pre>"); 
 
})();

0

Basta provare

throw new Error('some error here') 

Questo funziona abbastanza bene per Chrome:

enter image description here

2

Questo codice ovatta lavorare in (2017) i moderni browser (IE11 , Musica lirica, Chrome, FireFox, Yandex):

printStackTrace: function() { 
    var err = new Error(); 
    var stack = err.stack || /*old opera*/ err.stacktrace || (/*IE11*/ console.trace ? console.trace() : "no stack info"); 
    return stack; 
} 

altre risposte:

function stackTrace() { 
    var err = new Error(); 
    return err.stack; 
} 

non funziona in IE 11!

Utilizzo di arguments.callee.caller - non funziona in modalità rigorosa in alcun browser!

Problemi correlati