Javascript is a powerful tool in the web programmers toolbox however, it's also one of our greatest headaches. Dealing with browser inconsistencies is always a source of great pain. You test on multiple platforms, find everyone you know with a mac running safari and think you have your code locked down however it rarely always works out this way. Being able to detect javascript errors in the wild can be a great resource for you to really see how your code is performing on a day to day basis. Mozilla and IE support a powerful event handler called "onerror" used like window.onerror = function(){};
You can create a custom function at the top of all your scripts that will record any parsing or exception errors generated. You can create your function to accept 3 parameters, the message of the error, the URL of the error and the Line number of the error. Creating this function is as simple as so:
<SCRIPT>
window.onerror = function(msg, err_url, line) {
alert('an error occured on line: ' + line);
}
</SCRIPT>
Now the end user really doesn't care which line an error occurred on but the powerful part is being able to get this information back to the developers. Using AJAX technologies you can easily record a log of all js errors on your site so you can take appropriate action to fix these issues. Not only can you include msg, line and error URL, but you can also send any other information javascript can capture such as referring page and the type of browser the client is using.
// post data you want to send to the server
var POSTData = 'msg=' + msg ;
// create the actual xmlhttprequest object and pass the URL of the PHP page you want to call
var s = new XMLHTTP("error_server.php?");
// post data to the server and assign processReqChange as the function to call back when the data is posted
var xmlDoc = s.call(POSTData, processReqChange);
Putting these two things together you can now log all of your JS error msgs behind the scenes and create an offline viewer that you and your other programmers can sift through. I prefer to err on the side of performance so the goal is just to log some quick info to the server and set up a cron job to email that data each night to the developers.
FILE 1 - Our main HTML File index.html.So what we're doing here is first including our XMLHTTPRequest class to instantiate our JS Object, then including the onerror functionality that will log the data to our server on every webpage.
If you have better solution, just tell me !
0 comments:
Post a Comment