diff --git a/src/lib/utils.ts b/src/lib/utils.ts index badfe5f..824fd0d 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -128,13 +128,12 @@ export function canRaiseHTTPError( try { return await descriptor.value.apply(this, args); } catch (exc: any) { - if (axios.isAxiosError(exc) && exc.response) { - const errorData = exc.response.data as Record; - const ErrorKlass = getErrorClass(errorData.error.type); - throw new ErrorKlass(errorData.error); - } else { - throw exc; + const apiError = axios.isAxiosError(exc) ? exc.response?.data?.error : undefined; + if (apiError && typeof apiError === 'object' && typeof apiError.type === 'string') { + const ErrorKlass = getErrorClass(apiError.type); + throw new ErrorKlass(apiError); } + throw exc; } }; diff --git a/src/spec/utils/canRaiseHTTPError.spec.ts b/src/spec/utils/canRaiseHTTPError.spec.ts index a832f7c..85e2d2f 100644 --- a/src/spec/utils/canRaiseHTTPError.spec.ts +++ b/src/spec/utils/canRaiseHTTPError.spec.ts @@ -1,6 +1,6 @@ import test from 'ava'; -import { FintocError } from '../../lib/errors'; +import { FintocError, InvalidRequestError } from '../../lib/errors'; import { canRaiseHTTPError } from '../../lib/utils'; class Errors { @@ -28,6 +28,20 @@ class Errors { throwGenericError() { throw new Error(); } + + @canRaiseHTTPError + throwAxiosError(error: Error) { + throw error; + } +} + +function buildAxiosError(data: unknown) { + const error = new Error('Request failed with status code 400'); + // @ts-ignore: property does not exist + error.isAxiosError = true; + // @ts-ignore: property does not exist + error.response = { status: 400, data }; + return error; } test.beforeEach((t) => { @@ -53,3 +67,35 @@ test('"canRaiseHTTPError" generic error', async (t) => { await t.throwsAsync(ctx.errors.throwGenericError, { instanceOf: Error }); }); + +test('"canRaiseHTTPError" typed API error body', async (t) => { + const ctx: any = t.context; + const original = buildAxiosError({ + error: { type: 'invalid_request_error', message: 'Bad param' }, + }); + + await t.throwsAsync(() => ctx.errors.throwAxiosError(original), { + instanceOf: InvalidRequestError, + }); +}); + +const bodiesWithoutErrorType: [string, unknown][] = [ + ['string body', '400 Bad Request'], + ['HTML body', '

400 Bad Request

'], + ['empty object body', {}], + ['object body without error.type', { error: {} }], + ['non-object error', { error: 'Bad Request' }], + ['undefined body', undefined], + ['null body', null], +]; + +bodiesWithoutErrorType.forEach(([description, data]) => { + test(`"canRaiseHTTPError" re-throws the original error with ${description}`, async (t) => { + const ctx: any = t.context; + const original = buildAxiosError(data); + + const thrown = await t.throwsAsync(() => ctx.errors.throwAxiosError(original)); + + t.is(thrown, original); + }); +});