如何捕捉Javascript腳本錯誤并記錄到日志中?
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
一、xml httprequest和xml dom基礎 這兩個是web 開發的常用東西,就不說了,先看看使用:
二、javascript腳本錯誤處理基礎
請教大家一個問題?如何處理腳本錯誤的?又如何去捕捉腳本錯誤的?有沒有遇到過客戶打電話抱怨系統不能運行,而你判斷可能是客戶端問題后就不知道如何處理的情況? 最新的瀏覽器都支持try/catch方式捕捉javascript異常,還有一個onerror事件來處理異常。
三、將客戶端錯誤寫入服務器端的日志文件 首先,客戶端建立一個單例模式的對象logger // singleton class constructor function logger() { // fields this.req;
// methods this.errortoxml = errortoxml; this.log = log; } 其次,我們要把javascript錯誤序列化到xml對象中。默認情況下,error對象只有兩個屬性:name和message。我們需要再建立一個屬性:location。 // map an error to an xml document function errortoxml(err) { var xml = '<?xml version="1.0"?>\n' + '<error>\n' + '<name>' + err.name + '</name>\n' + '<message>' + err.message + '</message>\n'; if (err.location) xml += '<location>' + err.location + '</location>'; xml += '</error>'; return xml; } 接下來是利用xmlhttp請求將錯誤信息寫入到日志中,原文作者利用cgi寫入,這里,可以根據具體的應用情況選擇大家自己的處理方式: // log method of logger class function log(err) { // feature sniff if (window.xmlhttprequest) this.req = new xmlhttprequest(); else if (window.activexobject) this.req = new activexobject("microsoft.xmlhttp"); else return; // throw up our hands in despair // set the method and uri this.req.open("post", "/cgi-bin/ajaxlogger.cgi"); // set the request headers. referer will be the top-level // uri which may differ from the location of the error if // it occurs in an included .js file this.req.setrequestheader('referer', location.href); this.req.setrequestheader('content-type', 'text/xml'); // function to be called when the request is complete this.req.onreadystatechange = errorlogged; this.req.send(this.errortoxml(err)); // if the request doesn't complete in 10 seconds, // something is up this.timeout = window.settimeout("abortlog();", 10000); } 然后,我們要實例化這個類: // should only be one instance of the logger var logger = new logger(); 最后的兩個方法用來做“家務管理”的。 // we tried, but if there is a connection error, it is hopeless function abortlog() { logger.req.abort(); alert("attempt to log the error timed out."); }
// called when the state of the request changes function errorlogged() { if (logger.req.readystate != 4) return; window.cleartimeout(logger.timeout); // request completed if (logger.req.status >= 400) alert('attempt to log the error failed.'); }
好了,把前面講述的幾個方法封裝到一個公用腳本logger.js中去吧,然后你就可以enjoy了。
在自己開發的腳本中引入這個js并使用如下: 【stone評】有問題,有興趣者可調整。 <script type="text/javascript" src="logger.js"></script> <script type="text/javascript"> function traperror(msg, uri, ln) { // wrap our unknown error condition in an object var error = new error(msg); error.location = uri + ', line: ' + ln; // add custom property logger.log(error); warnuser(); return true; // stop the yellow triangle } window.onerror = traperror;
function foo() { try { riskyoperation(); } catch (err) { // add custom property err.location = location.href + ', function: foo()'; logger.log(err); warnuser(); } } function warnuser() { alert("an error has occurred while processing this page."+ "our engineers have been alerted!"); // drastic action location.href = '/path/to/error/page.html'; } </script>
最后是在服務器端利用cgi寫入日志,代碼如下,喜歡用別的方式的程序員可以選擇利用你們擅長的語言來將xml日志信息寫入服務器端文件。 use cgi; use cgi::carp qw(set_progname); use xml::simple; my $request = cgi->new();
my $method = $request->request_method(); # method must be post if ($method eq 'post') { eval { my $content_type = $request->content_type(); if ($content_type eq 'text/xml') { print $request->header(-status => '415 unsupported media type', -type => 'text/xml'); croak "invalid content type: $content_type\n"; } # when method is post and the content type is neither # uri encoded nor multipart form, the entire post # is stuffed into one param: postdata my $error_xml = $request->param('postdata'); my $ref = xml::simple::xmlin($error_xml); my ($name, $msg, $location) = ($ref->{'name'}, $ref->{'message'}, ''); $location = $ref->{'location'} if (defined($ref->{'location'})); # this will change the name of the carper in the log set_progname('client-side error'); my $remote_host = $request->remote_host(); carp "name: [$name], msg: [$msg], location: [$location]"; }; if ($@) { print $request->header(-status => '500 internal server error', -type => 'text/xml'); croak "error while logging: $@"; } else { # this response code indicates that the operation was a # success, but the client should not expect any content print $request->header(-status => '204 no content', -type => 'text/xml'); } } else { print $request->header(-status => '405 method not supported', -type => 'text/xml'); croak "unsupported method: $method"; } 該文章在 2010/8/13 8:24:27 編輯過 |
關鍵字查詢
相關文章
正在查詢... |