feat: 优化网络请求异常处理
All checks were successful
Egg CI/CD / build-image (push) Successful in 34s
Egg CI/CD / deploy (push) Successful in 23s

This commit is contained in:
zhaoyingbo 2024-06-13 09:08:13 +00:00
parent 4bd0e26455
commit 2197db3785
4 changed files with 84 additions and 44 deletions

View File

@ -26,11 +26,11 @@ const larkNetTool = async <T = LarkServer.BaseRes>({
data,
headers: headersWithAuth,
}).catch((error) => {
console.error("网络请求异常", error);
console.error("larkNetTool catch error: ", error);
return {
code: 1,
data: null,
msg: "网络请求异常",
msg: error.message || "网络请求异常",
} as T;
});
};

View File

@ -44,20 +44,47 @@ const get = async (user_id: string, user_id_type: string, isSeek = false) => {
};
/**
* 使get接口模拟批量获取用户信息
*
* @param user_ids
* @returns
*/
const batchGet = async (
user_ids: string[],
user_id_type: "open_id" | "user_id",
isSeek = false
) => {
const requestMap = user_ids.map((user_id) => {
return get(user_id, user_id_type, isSeek);
});
const URL = `https://open.f.mioffice.cn/open-apis/contact/v3/users/batch`;
const headers = isSeek
? {
Authorization: `Bearer ${await db.tenantAccessToken.getSeek()}`,
}
: {};
// 如果user_id长度超出50需要分批请求
const user_idsLen = user_ids.length;
const maxLen = 50;
const requestMap = Array.from(
{ length: Math.ceil(user_idsLen / maxLen) },
(_, index) => {
const start = index * maxLen;
const user_idsSlice = user_ids.slice(start, start + maxLen);
const getParams = `${user_idsSlice
.map((id) => `user_ids=${id}`)
.join("&")}&user_id_type=${user_id_type}`;
return larkNetTool.get<LarkServer.BatchUserInfoRes>(
URL,
getParams,
headers
);
}
);
const responses = await Promise.all(requestMap);
const items = responses.map((res) => {
return res.data.user;
const items = responses.flatMap((res) => {
return res.data?.items || [];
});
return {
code: 0,
data: {
@ -67,32 +94,6 @@ const batchGet = async (
};
};
// /**
// * 批量获取用户信息
// * @param user_ids
// * @returns
// */
// const batchGet = async (
// user_ids: string[],
// user_id_type: "open_id" | "user_id",
// isSeek = false
// ) => {
// const URL = `https://open.f.mioffice.cn/open-apis/contact/v3/users/batch`;
// const headers = isSeek
// ? {
// Authorization: `Bearer ${await db.tenantAccessToken.getSeek()}`,
// }
// : {};
// return larkNetTool.get<LarkServer.BatchUserInfoRes>(
// URL,
// {
// user_ids,
// user_id_type,
// },
// headers
// );
// };
const user = {
code2Login,
batchGet,

View File

@ -6,6 +6,33 @@ interface NetGetParams {
headers?: any;
}
/**
*
* @param response
* @param method
* @param data
*/
const logResponse = async (response: Response, method: string, data: any) => {
let responseData = null;
try {
responseData = await response.json();
} catch (error) {
responseData = "parse to json error";
}
const responseLog = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: response.headers,
url: response.url,
method: method,
requestBody: data,
responseBody: responseData as any,
};
console.log("🚀 ~ responseLog:", JSON.stringify(responseLog, null, 2));
return responseLog;
};
const netTool = <T = any>({
url,
method,
@ -15,8 +42,12 @@ const netTool = <T = any>({
}: NetGetParams): Promise<T> => {
let fullUrl = url;
if (params) {
const queryString = new URLSearchParams(params).toString();
fullUrl = `${url}?${queryString}`;
if (typeof params === "string") {
fullUrl = `${url}?${params}`;
} else {
const queryString = new URLSearchParams(params).toString();
fullUrl = `${url}?${queryString}`;
}
}
return fetch(fullUrl, {
@ -26,12 +57,20 @@ const netTool = <T = any>({
"Content-Type": "application/json",
...headers,
},
}).then((response) => {
if (!response.ok) {
throw new Error("网络响应异常");
}
return response.json() as Promise<T>;
});
})
.then((response) => logResponse(response, method, data))
.then((responseLog) => {
if (!responseLog.ok) {
if (responseLog?.responseBody?.msg) {
throw new Error(responseLog.responseBody.msg);
}
throw new Error("网络响应异常");
}
if (responseLog.responseBody === "parse to json error") {
throw new Error("解析响应数据异常");
}
return responseLog.responseBody as T;
});
};
netTool.get = <T = any>(url: string, params?: any, headers?: any): Promise<T> =>

View File

@ -7,9 +7,9 @@ const res = await fetch(localUrl, {
"Content-Type": "application/json",
},
body: JSON.stringify({
user_ids: ["libo12", "zhaoyingbo"],
user_ids: ["wangyifei", "zhaoyingbo"],
user_id_type: "user_id",
}),
});
console.log(JSON.stringify(await res.json()));
console.log(await res.json());