改写fetch方法:
- // fetch的处理
- function _errorFetchInit () {
- if(!window.fetch) return;
- let _oldFetch = window.fetch;
- window.fetch = function () {
- return _oldFetch.apply(this, arguments)
- .then(res => {
- if (!res.ok) { // 当status不为2XX的时候,上报错误
- }
- return res;
- })
- // 当fetch方法错误时上报
- .catch(error => {
- // error.message,
- // error.stack
- // 抛出错误并且上报
- throw error;
- })
- }
- }
对于XMLHttpRequest的重写:
xhr改写
- // xhr的处理
- function _errorAjaxInit () {
- let protocol = window.location.protocol;
- if (protocol === 'file:') return;
- // 处理XMLHttpRequest
- if (!window.XMLHttpRequest) {
- return;
- }
- let xmlhttp = window.XMLHttpRequest;
- // 保存原生send方法
- let _oldSend = xmlhttp.prototype.send;
- let _handleEvent = function (event) {
- try {
- if (event && event.currentTarget && event.currentTarget.status !== 200) {
- // event.currentTarget 即为构建的xhr实例
- // event.currentTarget.response
- // event.currentTarget.responseURL || event.currentTarget.ajaxUrl
- // event.currentTarget.status
- // event.currentTarget.statusText
- });
- }
- } catch (e) {va
- console.log('Tool's error: ' + e);
- }
- }
- xmlhttp.prototype.send = function () {
- this.addEventListener('error', _handleEvent); // 失败
- this.addEventListener('load', _handleEvent); // 完成
- this.addEventListener('abort', _handleEvent); // 取消
- return _oldSend.apply(this, arguments);
- }
- }
关于responseURL 的说明
需要特别注意的是,当请求完全无法执行的时候,XMLHttpRequest会收到status=0 和 statusText=null的返回,此时responseURL也为空string。
另外在安卓4.4及以下版本的webview中,xhr对象也不存在responseURL属性。 (编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|