Skip to content

Commit

Permalink
refactor(core): Throw an error when the document is not initialized.
Browse files Browse the repository at this point in the history
In case the document is accessed but not available we should throw ASAP an error to prevent non explicit errors.

Fixes angular#50138
  • Loading branch information
JeanMeche committed May 4, 2023
1 parent 2419c48 commit c4565fe
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
2 changes: 2 additions & 0 deletions goldens/public-api/core/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ export const enum RuntimeErrorCode {
// (undocumented)
INVALID_SKIP_HYDRATION_HOST = -504,
// (undocumented)
MISSING_DOCUMENT = 210,
// (undocumented)
MISSING_GENERATED_DEF = 906,
// (undocumented)
MISSING_HYDRATION_ANNOTATIONS = -505,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const enum RuntimeErrorCode {
PROVIDER_IN_WRONG_CONTEXT = 207,
MISSING_INJECTION_TOKEN = 208,
INVALID_MULTI_PROVIDER = -209,
MISSING_DOCUMENT = 210,

// Template Errors
MULTIPLE_COMPONENTS_MATCH = -300,
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/render3/interfaces/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/

import { RuntimeError, RuntimeErrorCode } from "../../errors";

/**
* Most of the use of `document` in Angular is from within the DI system so it is possible to simply
* inject the `DOCUMENT` token and are done.
Expand Down Expand Up @@ -47,6 +49,11 @@ export function getDocument(): Document {
} else if (typeof document !== 'undefined') {
return document;
}

if(typeof ngDevMode === 'undefined' || ngDevMode && !getDocument()) {
throw new RuntimeError(RuntimeErrorCode.MISSING_DOCUMENT, `The document is not available in this context. Make sure the DOCUMENT injection token is provided.`)
}

// No "document" can be found. This should only happen if we are running ivy outside Angular and
// the current platform is not a browser. Since this is not a supported scenario at the moment
// this should not happen in Angular apps.
Expand Down

0 comments on commit c4565fe

Please sign in to comment.