From 4e6c2372c4899bba38bedcb8f04bab928b4f8221 Mon Sep 17 00:00:00 2001 From: SkyZeroZx <73321943+SkyZeroZx@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:32:00 -0500 Subject: [PATCH 1/2] fix(@angular/ssr): wrap non-Error values thrown while rendering A value such as the `HttpErrorResponse` of a failed request in an app initializer was passed to the server as is, where Express reads its `status` and `headers`. This could leave the request unanswered or terminate the server process. `AngularAppEngine` now wraps it in an `Error`. Fixes #34801 --- packages/angular/ssr/node/src/app-engine.ts | 3 + packages/angular/ssr/src/app-engine.ts | 21 +++- packages/angular/ssr/src/app.ts | 13 ++- packages/angular/ssr/src/utils/error.ts | 27 +++++ packages/angular/ssr/test/app-engine_spec.ts | 108 +++++++++++++++++- packages/angular/ssr/test/utils/error_spec.ts | 68 +++++++++++ 6 files changed, 229 insertions(+), 11 deletions(-) create mode 100644 packages/angular/ssr/src/utils/error.ts create mode 100644 packages/angular/ssr/test/utils/error_spec.ts diff --git a/packages/angular/ssr/node/src/app-engine.ts b/packages/angular/ssr/node/src/app-engine.ts index 4bb6d28bb045..64e784efed13 100644 --- a/packages/angular/ssr/node/src/app-engine.ts +++ b/packages/angular/ssr/node/src/app-engine.ts @@ -59,6 +59,9 @@ export class AngularNodeAppEngine { * @param requestContext - Optional context for rendering, such as metadata associated with the request. * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found. * + * @throws {Error} If the application throws or rejects with a value that is not an `Error`, such as + * an `HttpErrorResponse`, it is wrapped in an `Error` with the original value as its `cause`. + * * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route * corresponding to `https://www.example.com/page`. * diff --git a/packages/angular/ssr/src/app-engine.ts b/packages/angular/ssr/src/app-engine.ts index e4629388183c..8c124e6fd540 100644 --- a/packages/angular/ssr/src/app-engine.ts +++ b/packages/angular/ssr/src/app-engine.ts @@ -10,6 +10,7 @@ import type { AngularServerApp, getOrCreateAngularServerApp } from './app'; import { Hooks } from './hooks'; import { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n'; import { EntryPointExports, getAngularAppEngineManifest } from './manifest'; +import { ensureError } from './utils/error'; import { createRedirectResponse } from './utils/redirect'; import { joinUrlParts } from './utils/url'; import { @@ -140,6 +141,9 @@ export class AngularAppEngine { * @param requestContext - Optional context for rendering, such as metadata associated with the request. * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found. * + * @throws {Error} If the application throws or rejects with a value that is not an `Error`, such as + * an `HttpErrorResponse`, it is wrapped in an `Error` with the original value as its `cause`. + * * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route * corresponding to `https://www.example.com/page`. * @@ -168,13 +172,18 @@ export class AngularAppEngine { return this.handleValidationError(error as Error, securedRequest); } - const serverApp = await this.getAngularServerAppForRequest(securedRequest); - if (serverApp) { - if (deoptToCSR) { - return serverApp.serveClientSidePage(); - } + try { + const serverApp = await this.getAngularServerAppForRequest(securedRequest); + if (serverApp) { + if (deoptToCSR) { + return await serverApp.serveClientSidePage(); + } - return serverApp.handle(securedRequest, requestContext); + return await serverApp.handle(securedRequest, requestContext); + } + } catch (error) { + // The application can reject with any value, e.g. an `HttpErrorResponse` from an app initializer. + throw ensureError(error); } if (this.supportedLocales.length > 1) { diff --git a/packages/angular/ssr/src/app.ts b/packages/angular/ssr/src/app.ts index 1b45b6e29fe3..027c7b275fd9 100644 --- a/packages/angular/ssr/src/app.ts +++ b/packages/angular/ssr/src/app.ts @@ -21,6 +21,7 @@ import { RenderMode } from './routes/route-config'; import { RouteTreeNodeMetadata } from './routes/route-tree'; import { ServerRouter } from './routes/router'; import { sha256 } from './utils/crypto'; +import { ensureError } from './utils/error'; import { InlineCriticalCssProcessor } from './utils/inline-critical-css'; import { LRUCache } from './utils/lru-cache'; import { AngularBootstrap, renderAngular } from './utils/ng'; @@ -365,10 +366,14 @@ export class AngularServerApp { // Use a stream to send the response before finishing rendering and inling critical CSS, improving performance via header flushing. const stream = new ReadableStream({ start: async (controller) => { - const renderedHtml = await result.content(); - const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url); - controller.enqueue(finalHtml); - controller.close(); + try { + const renderedHtml = await result.content(); + const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url); + controller.enqueue(finalHtml); + controller.close(); + } catch (error) { + controller.error(ensureError(error)); + } }, }); diff --git a/packages/angular/ssr/src/utils/error.ts b/packages/angular/ssr/src/utils/error.ts new file mode 100644 index 000000000000..ba8de41c9aed --- /dev/null +++ b/packages/angular/ssr/src/utils/error.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * Ensures that a value thrown while handling a request or rendering the application is an `Error`. + * + * An application can throw or reject with any value, such as an `HttpErrorResponse` from a failed + * `HttpClient` request. Passing non-`Error` values to server frameworks can cause unexpected + * behavior, such as Express's `finalhandler` setting non-header properties from `err.headers` or + * Fastify serializing the value as a `200 OK` JSON response. + * + * @param error - The value thrown by the application. + * @returns The value itself when it is an `Error`, otherwise an `Error` with the value as its `cause`. + */ +export function ensureError(error: unknown): Error { + return error instanceof Error + ? error + : new Error( + 'The application failed to render with a value that is not an Error instance. See its cause for the original value.', + { cause: error }, + ); +} diff --git a/packages/angular/ssr/test/app-engine_spec.ts b/packages/angular/ssr/test/app-engine_spec.ts index 9df4ec690c1c..69947a19a584 100644 --- a/packages/angular/ssr/test/app-engine_spec.ts +++ b/packages/angular/ssr/test/app-engine_spec.ts @@ -11,7 +11,7 @@ import '@angular/compiler'; /* eslint-enable import/no-unassigned-import */ -import { Component, REQUEST, inject } from '@angular/core'; +import { Component, REQUEST, inject, provideAppInitializer } from '@angular/core'; import { destroyAngularServerApp, getOrCreateAngularServerApp } from '../src/app'; import { AngularAppEngine } from '../src/app-engine'; import { setAngularAppEngineManifest } from '../src/manifest'; @@ -316,6 +316,112 @@ describe('AngularAppEngine', () => { }); }); + describe('App that rejects while bootstrapping', () => { + let rejectWith: unknown; + let entryPointRejectWith: unknown; + + // Shaped like an `HttpErrorResponse`: error-like, but not an `Error` instance. + const errorResponse = { + name: 'HttpErrorResponse', + message: 'Http failure response', + status: 503, + headers: { lazyInit: undefined }, + }; + + beforeAll(() => { + @Component({ + selector: 'app-home', + template: `Home works`, + }) + class HomeComponent {} + + setAngularAppEngineManifest({ + allowedHosts: ['example.com'], + entryPoints: { + '': async () => { + if (entryPointRejectWith !== undefined) { + throw entryPointRejectWith; + } + + setAngularAppTestingManifest( + [{ path: 'home', component: HomeComponent }], + [{ path: '**', renderMode: RenderMode.Server }], + undefined, + undefined, + undefined, + undefined, + [ + provideAppInitializer(() => + rejectWith === undefined ? undefined : Promise.reject(rejectWith), + ), + ], + ); + + return { + ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp, + ɵdestroyAngularServerApp: destroyAngularServerApp, + }; + }, + }, + basePath: '/', + supportedLocales: { 'en-US': '' }, + }); + }); + + beforeEach(() => { + rejectWith = undefined; + entryPointRejectWith = undefined; + // A new engine loads the entry point again, which resets the server app and its routes. + appEngine = new AngularAppEngine(); + spyOn(console, 'error'); + }); + + it('should reject with an Error when loading the entry point rejects with a non-Error value', async () => { + entryPointRejectWith = 'Entry point error'; + + const handle = appEngine.handle(new Request('https://example.com/home')); + + await expectAsync(handle).toBeRejectedWithError(Error, /not an Error/); + await expectAsync(handle).toBeRejectedWith( + jasmine.objectContaining({ cause: jasmine.is(entryPointRejectWith) }), + ); + }); + + it('should reject with an Error when route extraction rejects with a non-Error value', async () => { + rejectWith = errorResponse; + + const handle = appEngine.handle(new Request('https://example.com/home')); + + await expectAsync(handle).toBeRejectedWithError(Error, /not an Error/); + await expectAsync(handle).toBeRejectedWith( + jasmine.objectContaining({ cause: jasmine.is(rejectWith) }), + ); + }); + + it('should reject with an Error when rendering rejects with a non-Error value', async () => { + // Routes are extracted by the first request, so the second one only renders. + const response = await appEngine.handle(new Request('https://example.com/home')); + expect(await response?.text()).toContain('Home works'); + + rejectWith = errorResponse; + + const handle = appEngine.handle(new Request('https://example.com/home')); + + await expectAsync(handle).toBeRejectedWithError(Error, /not an Error/); + await expectAsync(handle).toBeRejectedWith( + jasmine.objectContaining({ cause: jasmine.is(rejectWith) }), + ); + }); + + it('should reject with the original error when the app rejects with an Error', async () => { + rejectWith = new Error('Bootstrap error'); + + await expectAsync(appEngine.handle(new Request('https://example.com/home'))).toBeRejectedWith( + jasmine.is(rejectWith), + ); + }); + }); + describe('Invalid host headers', () => { let consoleErrorSpy: jasmine.Spy; diff --git a/packages/angular/ssr/test/utils/error_spec.ts b/packages/angular/ssr/test/utils/error_spec.ts new file mode 100644 index 000000000000..be2d6eff3c28 --- /dev/null +++ b/packages/angular/ssr/test/utils/error_spec.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { ensureError } from '../../src/utils/error'; + +describe('Error Utils', () => { + describe('ensureError', () => { + it('should return the same instance when the value is an Error', () => { + const error = new Error('Render error'); + + expect(ensureError(error)).toBe(error); + }); + + it('should return the same instance when the value is an Error subclass', () => { + class HttpError extends Error { + readonly status = 503; + readonly headers = { 'retry-after': '120' }; + } + + const typeError = new TypeError('Type error'); + const httpError = new HttpError('Service unavailable'); + + expect(ensureError(typeError)).toBe(typeError); + expect(ensureError(httpError)).toBe(httpError); + }); + + it('should return the same instance when the value is an AbortError DOMException', () => { + const abortError = new DOMException('Request was aborted.', 'AbortError'); + + expect(ensureError(abortError)).toBe(abortError); + }); + + it('should wrap primitives, null and undefined in an Error with the value as its cause', () => { + for (const value of ['Render error', 503, false, Symbol('error'), null, undefined]) { + const error = ensureError(value); + + expect(error).toBeInstanceOf(Error); + expect(error.message).toMatch(/not an Error/); + expect(error.cause).toBe(value); + } + }); + + it('should wrap error-like plain objects in an Error with the object as its cause', () => { + const errorLike = { + name: 'HttpErrorResponse', + message: 'Http failure response for http://localhost/api: 503 Service Unavailable', + status: 503, + headers: { lazyInit: undefined }, + }; + + const error = ensureError(errorLike); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBe(errorLike as unknown as Error); + expect(error.message).toMatch(/not an Error/); + expect(error.cause).toBe(errorLike); + // The message and the properties read by server frameworks are not copied from the value. + expect(error.message).not.toContain(errorLike.message); + expect('status' in error).toBeFalse(); + expect('headers' in error).toBeFalse(); + }); + }); +}); From 9f8a57a75c5cfaa6a75d859d944ee5b7ae9221b2 Mon Sep 17 00:00:00 2001 From: SkyZeroZx <73321943+SkyZeroZx@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:32:04 -0500 Subject: [PATCH 2/2] fix(@angular/ssr): wrap non-Error values thrown while rendering in `CommonEngine` `CommonEngine.render()` now also rejects with an `Error` when the application throws another value, such as an `HttpErrorResponse`. Fixes #34801 --- .../node/src/common-engine/common-engine.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/angular/ssr/node/src/common-engine/common-engine.ts b/packages/angular/ssr/node/src/common-engine/common-engine.ts index 36745403a0a5..2666e61c7325 100644 --- a/packages/angular/ssr/node/src/common-engine/common-engine.ts +++ b/packages/angular/ssr/node/src/common-engine/common-engine.ts @@ -12,6 +12,7 @@ import { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/plat import * as fs from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { URL } from 'node:url'; +import { ensureError } from '../../../src/utils/error'; import { validateUrl } from '../../../src/utils/validation'; import { getAllowedHostsFromEnv } from '../environment-options'; import { attachNodeGlobalErrorHandlers } from '../errors'; @@ -213,12 +214,17 @@ export class CommonEngine { allowedHosts: ['*'], }; - return isBootstrapFn(moduleOrFactory) - ? renderApplication(moduleOrFactory, { - platformProviders: extraProviders, - ...commonRenderingOptions, - }) - : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions }); + try { + return await (isBootstrapFn(moduleOrFactory) + ? renderApplication(moduleOrFactory, { + platformProviders: extraProviders, + ...commonRenderingOptions, + }) + : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions })); + } catch (error) { + // The application can reject with any value, e.g. an `HttpErrorResponse` from an app initializer. + throw ensureError(error); + } } /** Retrieve the document from the cache or the filesystem */