Catch errors generated in Avascript and display in a div

Asked

Viewed 460 times

1

I have a div calling for log and would like to capture everything that is generated in the console, just below I Gero an index error to undefined a += 8;. The problem is that it only captures the first mistake.

  • How do I show all errors generated when opening the page?

  • And how do I show it whichever error that may be generated during the execution of the code?

var log = document.getElementById('log');

window.onerror = function(message, url, lineNumber) {  
  log.innerHTML += lineNumber + ":<br/>" + message + "<br/>In: " + url;
};

a += 8; //Index indefinido;
b += 5; //Index indefinido;
//funcaoindefinida(); //Função indefinida;
//var var = 0; //Palavra reservada;
<div id="log"></div>

I tried to work with try...catch(e) but also only takes the first error generated in the code

var log = document.getElementById('log');
try{
  a += 8; //Index indefinido;
  b += 5; //Index indefinido;
  //funcaoindefinida(); //Função indefinida;
  //var var = 0; //Palavra reservada;
}
catch(e){
  log.innerHTML += e.message;
}
<div id="log"></div>

  • But where do you get the first error on the console? It seems to me that the problem is there.

  • So @bigwn believed that the window.onerror worked that way, whenever there was an error in the window, the variable log would receive this error more.

  • It’s the opposite, the catch will prevent the error. I will leave, if no one responds, I test and try to answer.

  • look, I ran a test here and it worked: http://jsfiddle.net/a0Lx0cjy/2/

  • @Tobymosque the point is that it only takes the first error. In your case "worked" because the event click only makes generate 1 error, then it catches without problem. Marcelo, I believe it is not easy to do this (not to say impossible without being sure), because when an error of execution happens the script is interrupted see in this Toby’s jsfiddler that I modified

  • When a exception it for running, that’s why you can only recover the first error.

  • @Marcelobonifazio, what is the context where this error capture occurs? It seems to me that using a bug-checked IDE (Netbeans for example) would solve the problem

  • It is not @sanction, would be errors generated at runtime, not syntax, as index in an undefined array

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.