Skip to content

Commit 5d3baa1

Browse files
SkyZeroZxalan-agius4
authored andcommitted
fix(@angular/ssr): log errors thrown while destroying the platform
An error thrown by a destroy hook escaped the timer that destroys the platform and could terminate the server process. It is now logged. Fixes #34754 (cherry picked from commit d33a557)
1 parent 2a17078 commit 5d3baa1

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

‎packages/angular/ssr/src/utils/ng.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,11 @@ function asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {
267267
if (!platformRef.destroyed) {
268268
platformRef.destroy();
269269
}
270+
} catch (error) {
271+
// An error thrown by a destroy hook must not escape this macrotask,
272+
// otherwise it becomes an uncaught exception that can terminate the process.
273+
// eslint-disable-next-line no-console
274+
console.error('An error occurred while destroying the platform.', error);
270275
} finally {
271276
resolve();
272277
}

‎packages/angular/ssr/test/utils/ng_spec.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import '@angular/compiler';
1414
import {
1515
ApplicationRef,
1616
Component,
17+
OnDestroy,
1718
PlatformRef,
1819
inject,
1920
provideZonelessChangeDetection,
@@ -280,4 +281,43 @@ describe('renderAngular', () => {
280281
await setTimeout(0);
281282
expect(destroySpy).toHaveBeenCalledTimes(1);
282283
});
284+
285+
it('should log errors thrown by destroy hooks instead of leaving them uncaught', async () => {
286+
const error = new Error('Destroy hook error');
287+
const consoleErrorSpy = spyOn(console, 'error');
288+
289+
@Component({
290+
selector: 'app-root',
291+
template: 'Destroy hook error works',
292+
})
293+
class AppComponent implements OnDestroy {
294+
ngOnDestroy(): void {
295+
throw error;
296+
}
297+
}
298+
299+
const result = await renderAngular(
300+
BASE_HTML,
301+
(context) =>
302+
bootstrapApplication(
303+
AppComponent,
304+
{ providers: [provideZonelessChangeDetection()] },
305+
context,
306+
),
307+
new URL('http://localhost/'),
308+
[],
309+
'ssr',
310+
);
311+
312+
expect(result).toEqual(jasmine.objectContaining({ destroy: jasmine.any(Function) }));
313+
if (!('destroy' in result)) {
314+
return;
315+
}
316+
317+
await expectAsync(result.destroy()).toBeResolved();
318+
expect(consoleErrorSpy).toHaveBeenCalledOnceWith(
319+
'An error occurred while destroying the platform.',
320+
error,
321+
);
322+
});
283323
});

0 commit comments

Comments
 (0)