Log client side errors to the server [duplicate]

2019-03-27 16:12发布

问题:

Possible Duplicate:
Logging Clientside JavaScript Errors on Server

How can I log client side javascript errors to the server? I'm using jQuery and MVC.

回答1:

Since they're client-side errors, you'll have to send them to the server using XMLHttpRequest. You could use try...catch statements or window.onerror:

window.onerror = function (msg, url, line)
{
    var message = "Error in "+url+" on line "+line+": "+msg;
    $.post("logerror.aspx", { "msg" : message }); 
}

Be aware that line and url can be very inaccurate in IE versions prior to 8.



回答2:

You could use my log4javascript, which has an appender that uses XMLHttpRequest to log to the server:

var log = log4javascript.getLogger("serverLog");
var ajaxAppender = new log4javascript.AjaxAppender("clientlogger.jsp");
log.addAppender(ajaxAppender);

try {
    nonExistentFunction();
} catch(ex) {
    log.error("Something's gone wrong!", ex);
}