错误处理
网络异常
// ./xhr.ts
import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from './types'
import { parseHeaders } from './helpers/headers'
// ./src/xhr.ts
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
const { data = null, url, method = 'get', headers, responseType } = config
const request = new XMLHttpRequest()
if (responseType) {
request.responseType = responseType
}
request.open(method.toUpperCase(), url, true)
// ...
request.onerror = function handleError() {
reject(new Error('Network Error'))
}
//...
request.send(data)
})
}
处理超时异常
// ./src/type/index.ts
//...
export interface AxiosRequestConfig {
url: string
method?: Method
data?: any
params?: any
headers?: any
responseType?: XMLHttpRequestResponseType
timeout?: number
}
//...
// ./xhr.ts
import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from './types'
import { parseHeaders } from './helpers/headers'
// ./src/xhr.ts
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
const { data = null, url, method = 'get', headers, responseType, timeout } = config
const request = new XMLHttpRequest()
if (responseType) {
request.responseType = responseType
}
if (timeout) {
request.timeout = timeout
}
request.open(method.toUpperCase(), url, true)
//...
request.onerror = function handleError() {
reject(new Error('Network Error'))
}
request.ontimeout = function handleTimeout() {
reject(new Error(`Timeout of ${timeout} ms exceeded`))
}
//...
request.send(data)
})
}
处理非200状态码
// ./xhr.ts
import { AxiosRequestConfig, AxiosPromise,