Skip to content

Commit

Permalink
fix(upgrade): add try/catch when downgrading injectables
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 angular#37579
  • Loading branch information
sonukapoor committed Sep 2, 2020
1 parent 59c234c commit 57464e3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 8 additions & 2 deletions packages/upgrade/src/common/src/downgrade_injectable.ts
Expand Up @@ -79,8 +79,14 @@ 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 (e) {
throw new Error(
`Trying to get the Angular injector before bootstrapping the corresponding Angular module. Injector name: ${
token}`);
}
};
(factory as any)['$inject'] = [$INJECTOR];

Expand Down
15 changes: 14 additions & 1 deletion packages/upgrade/src/common/test/downgrade_injectable_spec.ts
Expand Up @@ -29,14 +29,15 @@ describe('downgradeInjectable', () => {
return {mockNg1Injector, mockNg2Injector};
};

it('should return an AngularJS annotated factory for the token', () => {
it('should return an AngularJS annotated factory for the token', (done: DoneFn) => {
const factory = downgradeInjectable('someToken');
expect(factory).toEqual(jasmine.any(Function));
expect((factory as any).$inject).toEqual([$INJECTOR]);

const {mockNg1Injector, mockNg2Injector} = setupMockInjectors();
expect(factory(mockNg1Injector)).toEqual('service value');
expect(mockNg2Injector.get).toHaveBeenCalledWith('someToken');
done();
});

it('should inject the specified module\'s injector when specifying a module name', () => {
Expand All @@ -48,4 +49,16 @@ describe('downgradeInjectable', () => {
expect(factory(mockNg1Injector)).toEqual('service value');
expect(mockNg2Injector.get).toHaveBeenCalledWith('someToken');
});

it('should throw error if injector is undefined', () => {
const factory = downgradeInjectable('someToken', 'someModule');
expect(factory).toEqual(jasmine.any(Function));
expect((factory as any).$inject).toEqual([$INJECTOR]);

const {mockNg1Injector} = setupMockInjectors('someModule');
const error =
'Trying to get the Angular injector before bootstrapping the corresponding Angular module. Injector name: someToken';
mockNg1Injector.get.and.throwError(error);
expect(() => factory(mockNg1Injector)).toThrowError(error);
});
});

0 comments on commit 57464e3

Please sign in to comment.