Showing posts with label catch error. Show all posts
Showing posts with label catch error. Show all posts

Saturday, March 14, 2009

Catch JS errors on web page or web applications

Here is a code snippet to catch the script errors which could be generated on your web application.

It should be such that when its development environment, it must show a alert message and when its production environment, it sends a email or logs into a table.

//
// Traps all js errors
function catchJSError(a,b,c,d) {
//var lines= document.body.innerHTML.split('\n');
//var errorline = lines[c];


// Get error line
var source = document.body.innerHTML;
source = source.split("\n");

var bugline = ((c-1) + ":" + source[c-1] + "\n" +
(c) + ":" + source[c] + "\n" +
(c+1) + ":" + source[c+1] + "\n"
);



var bug = "<b>JS Error:</b> " + a +
"<BR><b>Error in the file:</b> " + b +
"<BR><b>On Line:</b> " + c +
"<BR><b>Character:</b> " + (isIE==true)?event.errorCharacter:"0" +
"<BR><b>Window Title:</b> " + document.title +
"<BR><b>Error Type:</b> " + (isIE==true)?e.errorCode:"0" + "<BR><BR>";


var file = window.location.pathname;
file = file.substring (file.lastIndexOf("/"));

var subject = escape("JS error on " + window.location.host + " : " + file);

var live_servers = "prod.checkingserver.com";

// Send email if a live server
if (live_servers.indexOf(document.domain)>=0) {

sendAjaxRequest("reportJSError.do", "subject="+subject+"&bug="+ escape(bug) );
}
else
alert(bug.replace(/<b>/g,"").replace(/<\/B>/g,"").replace(/<BR>/g,"\\n"));


return false;
}
window.onerror=catchJSError;