How to save the JavaScript errors in file

2019-01-24 20:24发布

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

5条回答
ら.Afraid
2楼-- · 2019-01-24 20:35

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.
查看更多
女痞
3楼-- · 2019-01-24 20:38

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-24 20:41

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.

查看更多
做自己的国王
5楼-- · 2019-01-24 20:56

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

查看更多
beautiful°
6楼-- · 2019-01-24 20:57

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.

查看更多
登录 后发表回答