Skip to content

Instantly share code, notes, and snippets.

@davebarnwell
Last active January 3, 2018 15:49
Show Gist options
  • Save davebarnwell/fd391211d2a672b0d5b32644155d2fe3 to your computer and use it in GitHub Desktop.
Save davebarnwell/fd391211d2a672b0d5b32644155d2fe3 to your computer and use it in GitHub Desktop.
catch and log javascript errors to your server with no dependancy on 3rd party libs
window.MaximumErrorCount = 5; // Limit number of errors sent
// register error handler
window.onerror = function(errorMsg, file, lineNumber) {
window.errorCount = window.errorCount || 0;
window.errorCount++;
if (window.errorCount <= window.MaximumErrorCount) {
var request = new XMLHttpRequest(); // OK for IE8+
request.open('POST', '/jsError.php', true); // POST to URL
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send({
errorMessage: errorMsg,
file: file,
url: window.location.href,
lineNumber: lineNumber,
ua: navigator.userAgent
});
}
}
<?php
// Do something more robust in production to check it's a valid post etc
// also use Monolog or similar to log, but hey this is an example :)
$logMessage = sprintf(
'JS_ERROR[%s] URL[%s] on file[%s:%s] UA[%s]',
$_POST['errorMessage'],
$_POST['url'],
$_POST['file'],
$_POST['lineNumber'],
$_POST['ua']
);
error_log($logMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment