Skip to content

Commit

Permalink
Merge pull request #20 from icapps/feature/catch-error
Browse files Browse the repository at this point in the history
Catch error from translator and use default message
  • Loading branch information
knor-el-snor committed Jun 20, 2019
2 parents c05c71e + 909daa0 commit fb4b318
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/lib/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion tests/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('errorParser', () => {
let translateMock;

beforeEach(() => {
translateMock = jest.fn(() => {});
translateMock = jest.fn(() => { });
jest.spyOn(translator, 'getTranslator').mockImplementation(() => ({ translate: translateMock }));
});

Expand Down Expand Up @@ -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
});
});

0 comments on commit fb4b318

Please sign in to comment.