Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch error from translator and use default message #20

Merged
merged 1 commit into from
Jun 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
});
});