Skip to content

Commit

Permalink
chore: add a type guard for axios error
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyentoanit committed Apr 26, 2022
1 parent fcc1e05 commit 44f706d
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/helpers/api-client-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { USER_AGENT } from '../constants'
import {
APIConfigurationParameters,
DEFAULT_API_BASE_PATH,
ModelErrorContainer,
SellingPartnerMismatchRegionError,
SellingPartnerNotFoundRegionError,
} from '../types'
Expand All @@ -27,6 +28,16 @@ const regions = new Map<string, string[]>(
}),
)
export class ApiClientHelpers {
static isAPIModelError(
axiosError: AxiosError<unknown | ModelErrorContainer>,
): axiosError is AxiosError<ModelErrorContainer> {
const isError = (axiosError as AxiosError<ModelErrorContainer>).response?.data.errors.every(
(element) => 'code' in element && 'message' in element,
)

return !!isError
}

static getAxiosInstance(parameters: APIConfigurationParameters): AxiosInstance {
let axiosInstance: AxiosInstance
const { axios } = parameters
Expand Down Expand Up @@ -59,7 +70,11 @@ export class ApiClientHelpers {
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response,
(error: AxiosError) => {
throw apiErrorFactory(error)
if (ApiClientHelpers.isAPIModelError(error)) {
throw apiErrorFactory(error)
}

throw error
},
)

Expand Down

0 comments on commit 44f706d

Please sign in to comment.