5

Suppose a particular user is using Chrome, and gets a runtime error which is logged in Chrome's Console. I'd like to know what that error is. Currently I would have to reach out to the specific user, get them to open up the console and tell me what the error is (or send a screenshot).

Is there a way for me to automatically catch or log that error (regardless of what the error is) and send it to the server?

As a follow-up question is there a way to do this for all major browsers?

Allen S
  • 3,471
  • 4
  • 34
  • 46
  • There are various tools/libraries that do this. Have a look at [Sentry](https://www.getsentry.com/for/javascript/) for one example. – James Allardice Sep 30 '14 at 11:56
  • Possible duplicate of [Catch all JavaScript errors and send them to server](https://stackoverflow.com/questions/5328154/catch-all-javascript-errors-and-send-them-to-server) – Martin Omander Sep 10 '18 at 17:56

1 Answers1

4

You could wrap console.log and console.error with your logging method

var log = console.log;

console.log = function() {
    //Ajax post arguments to your server for logging
    return log.apply(console, arguments);
};

var error = console.error;

console.error = function() {
    //log arguments to server
    return error.apply(console, arguments); 
};
artm
  • 8,554
  • 3
  • 26
  • 43
  • 1
    What about errors that are generated by the browser and not something I specifically log myself? If the browser is unable to parse a JSON response (as an example) the browser will log an error. I'd like to know about it. Would the above take care of this scenario? – Allen S Sep 30 '14 at 12:05
  • No, it won't but it'll get logs and errors sent by any JS code. If you want to log browser errors as well you can use window.onerror = function (errorMsg, url, lineNumber) { //ajax log to server ('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber); }. HTML 5 onerror sends col, error as well. – artm Sep 30 '14 at 12:24
  • More details have been given in the following link for the questions of @AllenS: https://stackoverflow.com/questions/4844643/is-it-possible-to-trap-cors-errors – Ceylan B. Feb 04 '23 at 13:42