forked from crowetic/commerce
Improved error handling for the fetch api
This commit is contained in:
parent
20c08fcbb4
commit
9257b44c0d
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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 } = {}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user