2017-07-22 4 views
0

私はwindow.errorを使用して、すべてのクライアント側のエラーをキャプチャしようとしています。JavaScriptのキャプチャのエラー

Javascriptエラーで正常に動作していますが、ネットワークエラーやAJAXエラーなどのエラーはすべて取り込まれません。

これは私のコード(私はjQueryのを使用することはできませんので、.ajaxErrorを使用することはできません)です:

window.onerror = function(messageOrEvent, source, lineno, colno, error) { 
    console.log("Captured: " + messageOrEvent) 
} 

は、これが結果です: enter image description here

誰もが道を知っていますクライアント側のすべてのエラーをキャプチャするには?

おかげ

+0

jqueryが{error:err => throw err}する可能性があります。 –

+0

私はそれをグローバルに行う必要があります。私はすべての単一の機能を編集することはできません。とにかくありがとう:) –

+0

おそらくいくつかのXMLHttpRequest.prototype関数をオーバーライドします。 –

答えて

1

はたぶんデフォルトの要求オブジェクトの上にフック:

(function(orig){ 
    window.XMLHttpRequest=function(...args){ 
    var instance=new orig(...args); 
    instance.addEventListener("readyStateChange",function(){ 
    if(instance.status!==200){ 
     throw new Error(instance.status+":"+instance.statusText); 
    } 
    }); 
    return instance; 
}; 
})(XMLHttpRequest); 
+0

ありがとうございました。これは私が探していたものです。行くに服従するもの... args? –

+0

@marcos Aguayoは.apply(arguments)と同じですが、* restパラメータ* –

0

私は道を見つけました。これは私のコードです。私はこれがすべてのエラーをキャプチャすると思います。

// JavaScript Errors 
    window.onerror = function(messageOrEvent, source, lineno, colno, error) { 
     console.log("Captured: " + messageOrEvent) 
    } 

    // 404 FILES 
    window.addEventListener('error', function(e) { 
     console.log(e); 
    }, true); 

    // AJAX Errors 
    var open = window.XMLHttpRequest.prototype.open, 
     send = window.XMLHttpRequest.prototype.send; 

    function openReplacement(method, url, async, user, password) { 
     this._url = url; 
     return open.apply(this, arguments); 
    } 

    function sendReplacement(data) { 
     if(this.onreadystatechange) { 
     this._onreadystatechange = this.onreadystatechange; 
     } 
     this.onreadystatechange = onReadyStateChangeReplacement; 
     return send.apply(this, arguments); 
    } 

    function onReadyStateChangeReplacement() { 

     // CAPTURE HERE. 
     if(this.status != 200){ 
     console.log(this.responseURL + " " + this.status + " " + this.statusText); 
     } 

     if(this._onreadystatechange) { 
     return this._onreadystatechange.apply(this, arguments); 
     } 
    } 

    window.XMLHttpRequest.prototype.open = openReplacement; 
    window.XMLHttpRequest.prototype.send = sendReplacement; 
関連する問題