Home  >  Article  >  Web Front-end  >  How to Obtain Stack Trace Information in JavaScript?

How to Obtain Stack Trace Information in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-17 22:26:02383browse

How to Obtain Stack Trace Information in JavaScript?

stacktrace() Function for JavaScript Exceptions

Determining a JavaScript stack trace is accessible when JavaScript exceptions occur. However, acquiring a stack trace for custom exceptions thrown manually may require specific techniques.

For custom exceptions, the following script can be employed:

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);
}

Additionally, modern browsers offer the console.trace() function for capturing stack traces during debugging.

Updated Solution (2013):

A simpler approach is to utilize the Error object's stack property:

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

The above is the detailed content of How to Obtain Stack Trace Information in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn