代码实现
// request.ts
import axios, { AxiosRequestConfig } from "axios";
// 自定义ReuqestConfig
interface RetryConfg extends AxiosRequestConfig {
retry: number,
retryDelay: number,
retryCount?: number;
}
// 创建请求实例
const request = axios.create();
// 响应拦截
request.interceptors.response.use(res => {
return res;
}, err => {
const config: RetryConfg = err.config;
// 重试配置判断
if (!config || !config.retry) {
return Promise.reject(err);
}
// 重试次数判断
config.retryCount = config.retryCount || 0;
if (config.retryCount >= config.retry) {
return Promise.reject(err);
}
// 次数自增
config.retryCount++;
// 重试
return new Promise<void>((resolve) => {
// 延迟
setTimeout(() => {
resolve();
}, config.retryDelay || 0);
}).then(() => {
console.log(`retyrCount ==> : ${config.retryCount}`);
return request(config);
});
});
// 暴露导出
export default request;
export type { RetryConfg };
测试环境
// server.ts
import express from "express";
const app = express();
app.use(express.json());
app.post("/retry", (req, res) => {
console.log(`Path: Path: ${req.path}`);
return res.status(500)
.json({
code: 500,
message: "error"
});
});
const port = 3000;
app.listen(port, () => {
console.log(`The service starts on port ${port}.`);
});
测试代码
// client.ts
import request, { RetryConfg } from "./request";
const config: RetryConfg = {
retry: 3,
retryDelay: 3000,
url: "http://localhost:3000/retry",
method: "post"
};
request(config)
.then(res => {
console.log('res ==> ', res.data);
}).catch(err => {
if (err.response) {
console.log('err ==> ', err.response.data);
} else {
console.log('err ==> ', err.message);
}
});
测试结果
retyrCount ==> : 1
retyrCount ==> : 2
retyrCount ==> : 3
err ==> { code: 500, message: 'error' }