处理错误基本实现
网络异常onerror
request.onerror = err => {reject(new Error('Networe Error'))}
请求超时ontimeout
request.ontimeout = (err) => {reject(new Error(`Timeout of ${timeout}ms exceeded`))}
:::warning 注意: 需要在 onreadystatecchange里判断status===0,否则会执行handleResponse方法先,从而调用了resolve(response) :::
非200状态码
function handleResponse(response: AxiosResponse) {if (response.status >= 200 || response.status <= 300) {resolve(response)} else {reject(`request failed with status ${response.status}`)}}
错误信息增强
创建 AxiosError类
Object.setPrototypeOf(this, AxiosError.prototype) 是为了: 处理ts继承内置对象,找不到原型方法的问题
export class AxiosError extends Error {isAxiosError: boolean;request?: any;response?: AxiosResponse;code?: string;config: AxiosRequestConfig;constructor(message: string,config: AxiosRequestConfig,code?: string,request?: any,responese?: AxiosResponse,) {super(message)this.isAxiosError = truethis.config = configthis.code = codethis.request = requestthis.response = responese// https://github.com/microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-workObject.setPrototypeOf(this, AxiosError.prototype)}}// 定义工厂函数export function createError(message: string,config: AxiosRequestConfig,code?: string,request?: any,responese?: AxiosResponse,) {return new AxiosError(message,config,code,request,responese,)}
应用
替换所有的new Error,使用createError替换,例如:
request.onerror = () => {
reject(createError('Networe Error', config, null, request))
}
request.ontimeout = () => {
reject(createError(`Timeout of ${timeout}ms exceeded`, config, null, request))
}
导出所有类型定义
新建axios.ts,把之前index.ts复制进去并导出,index.ts直接使用axios。
并且通过export * from './types/index' 导出所有类型定义
import axios from "./axios";
export default axios
// 导出所有类型定义
export * from './types/index'
