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

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

Closed
Closed
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
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}`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realized that some browsers (for example, Firefox) do not include the message in err.stack. So, I switched to err.message || err. There shouldn't be anything too useful in the stacktrace for app developers anyway (it's mostly framework DI internals).

}
};
(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/);
});
});