fix(upgrade): add try/catch when downgrading injectables (#38671)

This commit improves the error thrown by the downgrade module with a more
descriptive message on why the downgrade is failing.

Closes #37579

PR Close #38671
This commit is contained in:
Sonu Kapoor 2020-08-22 08:38:05 -04:00 committed by Andrew Kushnir
parent 1373a98e25
commit 0ae00bb1f7
2 changed files with 18 additions and 2 deletions

View File

@ -79,8 +79,12 @@ export function downgradeInjectable(token: any, downgradedModule: string = ''):
validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);
try {
const injector: Injector = $injector.get(injectorKey);
return injector.get(token);
} catch (err) {
throw new Error(`Error while ${attemptedAction}: ${err.message || err}`);
}
};
(factory as any)['$inject'] = [$INJECTOR];

View File

@ -48,4 +48,16 @@ describe('downgradeInjectable', () => {
expect(factory(mockNg1Injector)).toEqual('service value');
expect(mockNg2Injector.get).toHaveBeenCalledWith('someToken');
});
it('should mention the injectable\'s name in the error thrown when failing to retrieve injectable',
() => {
const factory = downgradeInjectable('someToken');
expect(factory).toEqual(jasmine.any(Function));
expect((factory as any).$inject).toEqual([$INJECTOR]);
const {mockNg1Injector, mockNg2Injector} = setupMockInjectors();
mockNg2Injector.get.and.throwError('Mock failure');
expect(() => factory(mockNg1Injector))
.toThrowError(/^Error while instantiating injectable 'someToken': Mock failure/);
});
});