Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a simple stacktrace js example working?

I'm trying to get a very simple stacktrace.js example working. I'm trying to utilize the printStackTrace() method to do so.

Basically, I'm calling a buggy function that throws an error and a stack trace in the console. However, I want this error and stack trace displayed in the console stored inside a string and get that string printed instead.

For example if I run this function

function foo() {
  var x = y;
}

I get an uncaught reference error y is not defined

I need this stored inside a string instead.

So far, I've tried the following

var error = null;
function foo(){
    try {
        var x = y;
    } catch(e) {
        error = printStackTrace(e);
    }
}
foo();
console.log(error);

But it's printing a different stacktrace that I don't understand.

enter image description here

What's the correct way to use the printStackTrace method?

like image 409
Divyanth Jayaraj Avatar asked Dec 13 '25 20:12

Divyanth Jayaraj


1 Answers

Try something like,

  window.onerror = function(msg, file, line, col, error) {
    var callback = function(stackframes) {
      var stringifiedStack = stackframes.map(function(sf) {
        return sf.toString();
      }).join('\n');
      alert('msg: ' + msg + ' line: ' + line + ' col: ' + col + ' error: ' + error + ' file:' + file);
    };
    StackTrace.get().then(callback)
  };

Working Example:

window.onerror = function(msg, file, line, col, error) {
  StackTrace.fromError(error).then(callback).catch(errback);
}
var errback = function(err) { console.log(err.message);
};
var callback = function(stackframes) {
    var stringifiedStack = stackframes.map(function(sf) {
      return sf.toString();
    }).join('\n');  };
function fault() {

alert('Error will be invoked!')
  throw "Test Error"
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.0/stacktrace.js"></script>

<input id="a" type="button" value="Test Call!" onClick="fault();" />

but it seems that they have a bug.

like image 63
JSON Avatar answered Dec 15 '25 10:12

JSON



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!