简体   繁体   中英

How to save the JavaScript errors in file

Need a solution for saving log of JavaScript errors. For automated testing any site with support popular web browsers (IE, FF, Chrome).

The simple/best way to do:)

In simple steps:

  1. Write a JavaScript error trapping code.
  2. Add Ajax request/response module to send the trapped error to your server.
  3. at the server store your Javascript errors to a log/database.
  4. If needed, provide a functionality to access the log remotely.

Logging to a file on client-side has limitations:

  1. Supported only by IE (using ActiveX Objects)
  2. Obviously, files are stores on client side. Not at the server.

Most practical method is to look for an event onerror. try-catch is the best method, but you should know where in your code is possible to appear an error.

Here alert is used. It can be replaced with an ajax call to some server-side script/app which will be responsible for the database logging of the message. JavaScript by itself can`t access any file-system - server's or user's. This will only send info about the error. demo

window.onerror = function (msg, url, num) {
    alert("Error: " + msg + "\nURL: " + url + "\nLine: " + num);
    return true;
};
JS-made-poo();

Internet Explorer uses ActiveX, which may be useful in some kind of a logging application. But the user probably will receive a warning when the ActiveX is fired.

I don't believe there is anything inherent in Javascript to support this as Javascript doesn't get access to the client's filesystem. You'd need to build a browser module, application with an embedded browser, or maybe see if you could build an appropriate firebug extension.

Or collect errors in a JS variable and then submit them to a server to log them.

Easiest way to do this is to setup a page that you can hit with a post, and on error, post the errors to that page. This requires catching all errors though, so you'd need to wrap your page in a try {.. } catch (e) {.. } statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM