diff --git a/packages/angular/ssr/src/utils/ng.ts b/packages/angular/ssr/src/utils/ng.ts index df0d6b0cbe65..11f2111af0a7 100644 --- a/packages/angular/ssr/src/utils/ng.ts +++ b/packages/angular/ssr/src/utils/ng.ts @@ -267,6 +267,11 @@ function asyncDestroyPlatform(platformRef: PlatformRef): Promise { if (!platformRef.destroyed) { platformRef.destroy(); } + } catch (error) { + // An error thrown by a destroy hook must not escape this macrotask, + // otherwise it becomes an uncaught exception that can terminate the process. + // eslint-disable-next-line no-console + console.error('An error occurred while destroying the platform.', error); } finally { resolve(); } diff --git a/packages/angular/ssr/test/utils/ng_spec.ts b/packages/angular/ssr/test/utils/ng_spec.ts index b3855b6caa03..da8ec48980b8 100644 --- a/packages/angular/ssr/test/utils/ng_spec.ts +++ b/packages/angular/ssr/test/utils/ng_spec.ts @@ -14,6 +14,7 @@ import '@angular/compiler'; import { ApplicationRef, Component, + OnDestroy, PlatformRef, inject, provideZonelessChangeDetection, @@ -280,4 +281,43 @@ describe('renderAngular', () => { await setTimeout(0); expect(destroySpy).toHaveBeenCalledTimes(1); }); + + it('should log errors thrown by destroy hooks instead of leaving them uncaught', async () => { + const error = new Error('Destroy hook error'); + const consoleErrorSpy = spyOn(console, 'error'); + + @Component({ + selector: 'app-root', + template: 'Destroy hook error works', + }) + class AppComponent implements OnDestroy { + ngOnDestroy(): void { + throw error; + } + } + + const result = await renderAngular( + BASE_HTML, + (context) => + bootstrapApplication( + AppComponent, + { providers: [provideZonelessChangeDetection()] }, + context, + ), + new URL('http://localhost/'), + [], + 'ssr', + ); + + expect(result).toEqual(jasmine.objectContaining({ destroy: jasmine.any(Function) })); + if (!('destroy' in result)) { + return; + } + + await expectAsync(result.destroy()).toBeResolved(); + expect(consoleErrorSpy).toHaveBeenCalledOnceWith( + 'An error occurred while destroying the platform.', + error, + ); + }); });