From 574a52344639c2ca0ac2b841f3ab0f2ff9ce96e5 Mon Sep 17 00:00:00 2001 From: Yun Shan Date: Tue, 10 Oct 2023 22:09:11 +0800 Subject: [PATCH] =?UTF-8?q?request=E8=AF=B7=E6=B1=82=E4=B8=8D=E4=B8=BA2xx?= =?UTF-8?q?=E6=97=B6=E8=BF=9B=E5=85=A5=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86?= =?UTF-8?q?=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/request/index.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/request/index.ts b/src/request/index.ts index 576f04e..36e91a2 100644 --- a/src/request/index.ts +++ b/src/request/index.ts @@ -18,6 +18,12 @@ if (typeof globalThis === 'object' && Object.prototype.hasOwnProperty.call(globa let defaultResponseTransformer = (response: Response) => response.text(); let defaultUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'; +export class RequestError extends Error { + constructor(message: string, readonly response?: Response, readonly cause?: Error) { + super(message, cause); + } +} + export interface CommonRequestOptions extends RequestInit { /** * 是否加时间戳,用于绕过缓存 @@ -84,6 +90,9 @@ async function request(url: string | URL, options: CommonRequestOpti const request = createRequest(url, options); return await fetch(request) .then((res) => { + if (!res.ok) { + throw new RequestError('获取响应失败,可能是临时网络波动,如果长时间失败请联系开发者', res); + } if (options.responseTransformer) { return options.responseTransformer(res); } @@ -91,7 +100,7 @@ async function request(url: string | URL, options: CommonRequestOpti }) .catch((err: Error) => { if (err.name === 'AbortError') { - throw new Error(`请求超时,强制停止请求(${String(timeout)}ms)`); + throw new RequestError(`请求超时,强制停止请求(${String(timeout)}ms)`); } throw err; }) @@ -135,4 +144,5 @@ export const Http = { setDefaultUserAgent(userAgent: string) { defaultUserAgent = userAgent; }, + RequestError, };