codingsplash
codingsplash

Reputation: 5045

printing stack trace of javascript console

I am trying to type a javascript code in an textarea and display the result of it in a div. I went through a similar question: showing-console-errors-and-alerts-in-a-div-inside-the-page

It works fine for any explicit console statements. But when there are any syntax errors in the code written in the text area, the error message is shown on only in the console and not captured in the code.

The code I am using is:

if (typeof console  != "undefined") 
    if (typeof console.log != 'undefined')
        console.olog = console.log;
    else
        console.olog = function() {};

    console.log = function(message) {
    console.olog(message);
    $('#result').append('<p>' + message + '</p>');
};
console.error = console.debug = console.info =  console.log

This works if I type console.log("hello") in the textarea. But when I type console.log("he deliberately, the error is shown only in the browser console. Is there a way I can capture such messages and display it?

Upvotes: 0

Views: 842

Answers (2)

kyriosli
kyriosli

Reputation: 333

You can use window.onerror to solve the problem, try

window.onerror = function(e) {
  console.log(e.stack);
}

Upvotes: 0

JNF
JNF

Reputation: 3730

Same way browser console does it.

Add try...catch to your code.

Upvotes: 2

Related Questions