feat: 优化netTool,解析响应数据异常时抛出错误
All checks were successful
Egg CI/CD / build-image (push) Successful in 27s
Egg CI/CD / deploy (push) Successful in 20s

This commit is contained in:
zhaoyingbo 2024-07-12 09:53:05 +00:00
parent 98dd30a572
commit af2ee9a775

View File

@ -79,21 +79,26 @@ const netTool = async <T = any>({
});
// 获取响应数据
let resData: any = null;
let resText: string = "";
try {
resData = await res.json();
} catch (error) {
resData = "解析为JSON时出错";
}
resText = await res.text();
resData = JSON.parse(resText);
} catch {}
// 记录响应
logResponse(res, method, headers, payload, resData);
logResponse(res, method, headers, payload, resData || resText);
if (!res.ok) {
if (resData?.msg) {
throw new Error(resData.msg);
}
if (resText) {
throw new Error(resText);
}
throw new Error("网络响应异常");
}
if (resData === "解析为JSON时出错") {
// http 错误码正常,但解析异常
if (!resData) {
throw new Error("解析响应数据异常");
}
return resData as T;