Skip to content

Commit

Permalink
fix(upgrade): add try/catch when downgrading injectables (#38671)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
sonukapoor authored and AndrewKushnir committed Sep 10, 2020
1 parent 7669bd8 commit 5de2ac3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
8 changes: 6 additions & 2 deletions packages/upgrade/src/common/src/downgrade_injectable.ts
Expand Up @@ -79,8 +79,12 @@ export function downgradeInjectable(token: any, downgradedModule: string = ''):

validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);

const injector: Injector = $injector.get(injectorKey);
return injector.get(token);
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];

Expand Down
12 changes: 12 additions & 0 deletions packages/upgrade/src/common/test/downgrade_injectable_spec.ts
Expand Up @@ -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/);
});
});

0 comments on commit 5de2ac3

Please sign in to comment.