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 394f6a0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 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
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 throw an 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 394f6a0

Please sign in to comment.