From 909daa0118a254e6f4d91964bcd6cb47fcdf636a Mon Sep 17 00:00:00 2001 From: Brent Van Geertruy Date: Thu, 20 Jun 2019 15:42:27 +0200 Subject: [PATCH] Catch error from translator and use default message --- src/lib/parser.ts | 7 ++++++- tests/parser.test.ts | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/lib/parser.ts b/src/lib/parser.ts index 4abcdc0..db9f216 100644 --- a/src/lib/parser.ts +++ b/src/lib/parser.ts @@ -37,7 +37,12 @@ export function parseErrors(error: any, translatorOptions?: TranslatorOptions) { if (translatorOptions) { const translator = getTranslator(translatorOptions.path, translatorOptions.defaultLocale); - translatedMessage = translator.translate(error.i18n); + try { + translatedMessage = translator.translate(error.i18n); + } catch (_error) { + // If language file was not found set text to default message + translatedMessage = error.message; + } // if the translatedMessage equals the error code OR is undefined because not found // fallback to default error message from errors diff --git a/tests/parser.test.ts b/tests/parser.test.ts index 5b96f05..9c73992 100644 --- a/tests/parser.test.ts +++ b/tests/parser.test.ts @@ -10,7 +10,7 @@ describe('errorParser', () => { let translateMock; beforeEach(() => { - translateMock = jest.fn(() => {}); + translateMock = jest.fn(() => { }); jest.spyOn(translator, 'getTranslator').mockImplementation(() => ({ translate: translateMock })); }); @@ -144,6 +144,19 @@ describe('errorParser', () => { expect(translateMock).toHaveBeenCalledTimes(1); }); + it('Should use default message when translator throws an error', () => { + translateMock.mockImplementation(() => { throw new Error('Error finding file'); }); + + const parsedError = parseErrors(new ApiError(httpStatus.BAD_REQUEST, errors.INVALID_INPUT), { path: '', language: 'du' }); + expect(parsedError).toMatchObject({ + id: expect.any(String), + status: httpStatus.BAD_REQUEST, + code: errors.INVALID_INPUT.code, + title: errors.INVALID_INPUT.message, + detail: errors.INVALID_INPUT.message, + }); + }); + // TODO: Custom cases }); });