Last active
January 3, 2018 15:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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