Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/angular/ssr/node/src/app-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
*
Expand Down
18 changes: 12 additions & 6 deletions packages/angular/ssr/node/src/common-engine/common-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 */
Expand Down
21 changes: 15 additions & 6 deletions packages/angular/ssr/src/app-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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`.
*
Expand Down Expand Up @@ -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) {
Expand Down
13 changes: 9 additions & 4 deletions packages/angular/ssr/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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));
}
Comment thread
SkyZeroZx marked this conversation as resolved.
Resolved
},
});

Expand Down
27 changes: 27 additions & 0 deletions packages/angular/ssr/src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -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 },
);
}
108 changes: 107 additions & 1 deletion packages/angular/ssr/test/app-engine_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;

Expand Down
68 changes: 68 additions & 0 deletions packages/angular/ssr/test/utils/error_spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
});
Loading