Improved error handling for the fetch api

This commit is contained in:
Luis Alvarez 2020-10-19 21:48:22 -05:00
parent 20c08fcbb4
commit 9257b44c0d
3 changed files with 17 additions and 12 deletions

View File

@ -4,12 +4,14 @@ export class BigcommerceGraphQLError extends Error {}
export class BigcommerceApiError extends Error {
status: number
res: Response
data: any
constructor(msg: string, res: Response) {
constructor(msg: string, res: Response, data?: any) {
super(msg)
this.name = 'BigcommerceApiError'
this.status = res.status
this.res = res
this.data = data
}
}

View File

@ -23,7 +23,7 @@ export default async function fetchGraphqlApi<Q, V = any>(
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
throw new Error('Failed to fetch BigCommerce API')
}
return json.data
}

View File

@ -24,13 +24,22 @@ export default async function fetchStoreApi<T>(
)
}
const contentType = res.headers.get('Content-Type')
const isJSON = contentType?.includes('application/json')
if (!res.ok) {
throw new BigcommerceApiError(await getErrorText(res), res)
const data = isJSON ? await res.json() : await getTextOrNull(res)
const headers = getRawHeaders(res)
const msg = `Big Commerce API error (${
res.status
}) \nHeaders: ${JSON.stringify(headers, null, 2)}\n${
typeof data === 'string' ? data : JSON.stringify(data, null, 2)
}`
throw new BigcommerceApiError(msg, res, data)
}
const contentType = res.headers.get('Content-Type')
if (!contentType?.includes('application/json')) {
if (!isJSON) {
throw new BigcommerceApiError(
`Fetch to Bigcommerce API failed, expected JSON content but found: ${contentType}`,
res
@ -41,12 +50,6 @@ export default async function fetchStoreApi<T>(
return res.status === 204 ? null : await res.json()
}
async function getErrorText(res: Response) {
return `Big Commerce API error (${res.status}) \n${JSON.stringify(
getRawHeaders(res)
)}\n ${await getTextOrNull(res)}`
}
function getRawHeaders(res: Response) {
const headers: { [key: string]: string } = {}