From 68735659a00afb1cf75f0434db95d2f3e2e226df Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Wed, 6 May 2020 10:19:36 +0800 Subject: [PATCH] fix: resolve fetch errors --- src/platforms/GitHub/API.ts | 49 ++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/platforms/GitHub/API.ts b/src/platforms/GitHub/API.ts index e5e0272..eb5b973 100644 --- a/src/platforms/GitHub/API.ts +++ b/src/platforms/GitHub/API.ts @@ -26,33 +26,36 @@ async function request( if (accessToken) { headers.Authorization = `token ${accessToken}` } + + let res: Response try { - const res = await fetch(url, { headers }) - const contentType = res.headers.get('Content-Type') || res.headers.get('content-type') - const isJson = contentType?.includes('application/json') - // About res.ok: - // True if res.status between 200~299 - // Ref: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok - if (res.ok) { - if (isJson) return res.json() - throw new Error(`Response content type is "${contentType}"`) - } else { - if (res.status === 404 || res.status === 401) throw new Error(errors.NOT_FOUND) - else if (res.status === 403) throw new Error(errors.API_RATE_LIMIT) - else if (res.status === 500) throw new Error(errors.SERVER_FAULT) - else if (isJson) { - const content = await res.json() - if (apiRateLimitExceeded(content)) throw new Error(errors.API_RATE_LIMIT) - if (isEmptyProject(content)) throw new Error(errors.EMPTY_PROJECT) - if (isBlockedProject(content)) throw new Error(errors.BLOCKED_PROJECT) - throw new Error(`Unknown message content "${content?.message}"`) - } else { - throw new Error(`Response content type is "${contentType}"`) - } - } + res = await fetch(url, { headers }) } catch (err) { throw new Error(errors.CONNECTION_BLOCKED) } + + const contentType = res.headers.get('Content-Type') || res.headers.get('content-type') + const isJson = contentType?.includes('application/json') + // About res.ok: + // True if res.status between 200~299 + // Ref: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok + if (res.ok) { + if (isJson) return res.json() + throw new Error(`Response content type is "${contentType}"`) + } else { + if (res.status === 404 || res.status === 401) throw new Error(errors.NOT_FOUND) + else if (res.status === 403) throw new Error(errors.API_RATE_LIMIT) + else if (res.status === 500) throw new Error(errors.SERVER_FAULT) + else if (isJson) { + const content = await res.json() + if (apiRateLimitExceeded(content)) throw new Error(errors.API_RATE_LIMIT) + if (isEmptyProject(content)) throw new Error(errors.EMPTY_PROJECT) + if (isBlockedProject(content)) throw new Error(errors.BLOCKED_PROJECT) + throw new Error(`Unknown message content "${content?.message}"`) + } else { + throw new Error(`Response content type is "${contentType}"`) + } + } } export async function getRepoMeta(