如何解决如何强制 XMLHttpRequest 响应错误?
假设我想在特定 URL 上模拟网络中的错误,我是这样开始的:
let intercepts = {}
let hasStubbedRequests = false
class Intercept {
url: string | RegExp
method?: string
error: string
constructor({ url,method,error }) {
this.url = url
this.method = method
this.error = error
}
match({ url,method }) {
const matchesUrl = this.url instanceof RegExp ?
this.url.test(url) :
this.url === url
const matchesMethod = this.method ?
this.method === method :
true
return matchesUrl && matchesMethod
}
}
const getXHRIntercept = (xhr) => {
for (const key in intercepts) {
let intercept = intercepts[key]
const request = {
url: xhr.
}
if (intercept.match(request)) {
intercept.queue()
return true
}
}
return false
}
const getFetchIntercept = (options = {}) => {
}
const stubRequests = () => {
if (hasStubbedRequests) {
return
}
const originalOpen = XMLHttpRequest.prototype.open
XMLHttpRequest.prototype.open = function(method,url) {
this.__method__ = method
this.__url__ = url
return originalOpen.apply(this,arguments)
}
const originalSend = XMLHttpRequest.prototype.send
XMLHttpRequest.prototype.send = function(){
const intercept = getXHRIntercept(this)
if (intercept) {
const respondWithError = () => {
}
setTimeout(respondWithError,100)
} else {
return originalSend.apply(this,arguments)
}
}
const originalFetch = window.fetch
window.fetch = function(url,options = {}){
if (getFetchIntercept({ ...options,url })) {
return new Promise(() => {
})
} else {
return originalFetch.apply(this,arguments)
}
}
}
我现在面临的问题是,如何向 XMLHttpRequest 返回错误?所以我基本上对请求进行存根,但为 XMLHttpRequest 调用正确的错误处理程序。
我想这样做,以便错误返回。错误应该调用正确的错误处理程序,但是否有不止一种方法可以做到这一点?例如 xhr.onerror
与 xhr.triggerEvent(...)
?我不知道如何正确地做到这一点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。