import { IBehaviorItemType, TrackerEvents } from './monitorEnum' function generateRequestError(requestOption, response) { const { url, header, method } = requestOption return { url, header, method, params: requestOption.data, response: response.data, statusCode: response.statusCode } } function generateUploadError(requestOption, response) { const { url, header } = requestOption return { url, header, params: requestOption.data, response: response.data, statusCode: response.statusCode } } export function rewriteRequest(monitor) { const originRequest = wx.request Object.defineProperty(wx, 'request', { configurable: false, enumerable: false, writable: false, value: function (options) { const originSuccess = options.success const originFail = options.fail monitor.pushBehaviorItem({ belong: 'request', method: options.url, activePage: null, type: IBehaviorItemType.http, args: null }) /** * 后期业务逻辑需要抽出来 * @param {...any} args */ options.success = function (...args) { typeof originSuccess === 'function' && originSuccess.call(this, ...args) if (options.monitorIgnore) return const response = args[0] let error = generateRequestError(options, response) let { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { let code = data.code if (code != 0) { monitor.handleErrorEvent(TrackerEvents.reqError, error) } } else { monitor.handleErrorEvent(TrackerEvents.reqError, error) } } /** 请求错误 */ options.fail = function (...args) { typeof originFail === 'function' && originFail.call(this, ...args) if (options.monitorIgnore) return let error = generateUploadError(options, { data: args[0] }) monitor.handleErrorEvent(TrackerEvents.reqError, error) } return originRequest.call(this, options) } }) } export function rewriteUpload(monitor) { const originUpload = wx.uploadFile Object.defineProperty(wx, 'uploadFile', { configurable: false, enumerable: false, writable: false, value: function (options) { const originSuccess = options.success const originFail = options.fail /** * 后期业务逻辑需要抽出来 * @param {...any} args */ options.success = function (...args) { typeof originSuccess === 'function' && originSuccess.call(this, ...args) const response = args[0] let error = generateUploadError(options, response) let { statusCode } = response if (statusCode < 200 || statusCode >= 300) { monitor.handleErrorEvent(TrackerEvents.uploadError, error) } } /** 请求错误 */ options.fail = function (...args) { typeof originFail === 'function' && originFail.call(this, ...args) monitor.handleErrorEvent(TrackerEvents.uploadError, args[0]) } return originUpload.call(this, options) } }) }