This code shows how to handle a JavaScript error by posting the details back to the server to be logged. This code can be wired up to use any logging system.
The errors.js file establishes a handler for window.onerror
to call the handleError
function. The handleError
function creates a web request (using the createHttpRequest
function in httpRequests.js) and posts the error details back to LogJavascriptError.aspx. The LogJavascriptError.aspx file then logs the details to the file.
errors.js
var applicationPath = '';
function handleError(msg, srcUrl, line){
var receiveReq = createHttpRequest();
var url = applicationPath + '/Admin/LogJavascriptError.aspx';
var data = "ErrorData=" + msg + "&SourcePage=" + srcUrl + "&Line=" + line;
receiveReq.open("POST", url, true);
receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
receiveReq.setRequestHeader("Content-length", data.length);
receiveReq.setRequestHeader("Connection", "close");
receiveReq.send(data);
}
window.onerror=handleError;
http://code.google.com/p/sitestarter/source/browse/trunk/Src/App/WWW/js/errors.js[^]
httpRequests.js
function createHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser doesn't support the XmlHttpRequest object. Please upgrade to Firefox.");
}
}
http://code.google.com/p/sitestarter/source/browse/trunk/Src/App/WWW/js/httpRequests.js[^]
LogJavascriptError.aspx
string errorData = Request.Form["ErrorData"];
string sourcePage = Request.Form["SourcePage"];
string line = Request.Form["Line"];
string full = "Javascript error: " + errorData + Environment.NewLine +
"Location: " + sourcePage + ", line " + line;
LogWriter.Error(full);
Response.Write("Done");
http://code.google.com/p/sitestarter/source/browse/trunk/Src/App/WWW/Admin/LogJavascriptError.aspx[^]