fix(service-worker): avoid uncaught rejection warning when registration fails (#30876)

Service worker API `navigator.serviceWorker.register` can fail in multiple ways.
For example, in Chrome, with an unstable network connection you can have the
following error: `An unknown error occurred when fetching the script.`

In the current state, it creates an `Uncaught (in promise) TypeError:` style of
error, which cannot be caught by the user on his own.

I think it's better to log the error over raising an error that cannot be
caught.

PR Close #30876
This commit is contained in:
Hoel IRIS 2019-06-04 16:54:24 +02:00 committed by Misko Hevery
parent 297222f892
commit 81c2a94310
2 changed files with 16 additions and 4 deletions

View File

@ -115,10 +115,11 @@ export function ngswAppInitializer(
} }
} }
// Don't return anything to avoid blocking the application until the SW is registered or // Don't return anything to avoid blocking the application until the SW is registered.
// causing a crash if the SW registration fails. // Catch and log the error if SW registration fails to avoid uncaught rejection warning.
readyToRegister$.pipe(take(1)).subscribe( readyToRegister$.pipe(take(1)).subscribe(
() => navigator.serviceWorker.register(script, {scope: options.scope})); () => navigator.serviceWorker.register(script, {scope: options.scope})
.catch(err => console.error('Service worker registration failed with:', err)));
}; };
return initializer; return initializer;
} }

View File

@ -28,7 +28,9 @@ describe('ServiceWorkerModule', () => {
return appRef.isStable.pipe(filter(Boolean), take(1)).toPromise(); return appRef.isStable.pipe(filter(Boolean), take(1)).toPromise();
}; };
beforeEach(() => swRegisterSpy = spyOn(navigator.serviceWorker, 'register')); beforeEach(
() => swRegisterSpy =
spyOn(navigator.serviceWorker, 'register').and.returnValue(Promise.resolve()));
describe('register()', () => { describe('register()', () => {
const configTestBed = async(opts: SwRegistrationOptions) => { const configTestBed = async(opts: SwRegistrationOptions) => {
@ -67,6 +69,15 @@ describe('ServiceWorkerModule', () => {
expect(TestBed.get(SwUpdate).isEnabled).toBe(true); expect(TestBed.get(SwUpdate).isEnabled).toBe(true);
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined});
}); });
it('catches and a logs registration errors', async() => {
const consoleErrorSpy = spyOn(console, 'error');
swRegisterSpy.and.returnValue(Promise.reject('no reason'));
await configTestBed({enabled: true, scope: 'foo'});
expect(consoleErrorSpy)
.toHaveBeenCalledWith('Service worker registration failed with:', 'no reason');
});
}); });
describe('SwRegistrationOptions', () => { describe('SwRegistrationOptions', () => {