How to save the JavaScript errors in file

偶尔善良 提交于 2019-12-18 03:48:50

问题


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


回答1:


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.




回答2:


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:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/6638132/how-to-save-the-javascript-errors-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!