-
Notifications
You must be signed in to change notification settings - Fork 27.2k
Expand file tree
/
Copy patherror_handler.ts
More file actions
175 lines (164 loc) Β· 5.26 KB
/
error_handler.ts
File metadata and controls
175 lines (164 loc) Β· 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* @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 {ENVIRONMENT_INITIALIZER} from './di/initializer_token';
import {InjectionToken} from './di/injection_token';
import {inject} from './di/injector_compatibility';
import type {EnvironmentProviders} from './di/interface/provider';
import {makeEnvironmentProviders, provideEnvironmentInitializer} from './di/provider_collection';
import {EnvironmentInjector} from './di/r3_injector';
import {DOCUMENT} from './document';
import {RuntimeError, RuntimeErrorCode} from './errors';
import {DestroyRef} from './linker/destroy_ref';
import {NgZone} from './zone/ng_zone';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
*
* ```ts
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* // Provide in standalone apps
* bootstrapApplication(AppComponent, {
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
*
* // Provide in module-based apps
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*
* @see [Unhandled errors in Angular](best-practices/error-handling)
*
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
this._console.error('ERROR', error);
}
}
/**
* `InjectionToken` used to configure how to call the `ErrorHandler`.
*/
export const INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken<(e: any) => void>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '',
{
factory: () => {
// The user's error handler may depend on things that create a circular dependency
// so we inject it lazily.
const zone = inject(NgZone);
const injector = inject(EnvironmentInjector);
let userErrorHandler: ErrorHandler;
return (e: unknown) => {
zone.runOutsideAngular(() => {
if (injector.destroyed && !userErrorHandler) {
setTimeout(() => {
throw e;
});
} else {
userErrorHandler ??= injector.get(ErrorHandler);
userErrorHandler.handleError(e);
}
});
};
},
},
);
export const errorHandlerEnvironmentInitializer = {
provide: ENVIRONMENT_INITIALIZER,
useValue: () => {
const handler = inject(ErrorHandler, {optional: true});
if ((typeof ngDevMode === 'undefined' || ngDevMode) && handler === null) {
throw new RuntimeError(
RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP,
`A required Injectable was not found in the dependency injection tree. ` +
'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.',
);
}
},
multi: true,
};
const globalErrorListeners = new InjectionToken<void>(
typeof ngDevMode !== 'undefined' && ngDevMode ? 'GlobalErrorListeners' : '',
{
factory: () => {
if (typeof ngServerMode !== 'undefined' && ngServerMode) {
return;
}
const window = inject(DOCUMENT).defaultView;
if (!window) {
return;
}
const errorHandler = inject(INTERNAL_APPLICATION_ERROR_HANDLER);
const rejectionListener = (e: PromiseRejectionEvent) => {
errorHandler(e.reason);
e.preventDefault();
};
const errorListener = (e: ErrorEvent) => {
if (e.error) {
errorHandler(e.error);
} else {
errorHandler(
new Error(
ngDevMode
? `An ErrorEvent with no error occurred. See Error.cause for details: ${e.message}`
: e.message,
{cause: e},
),
);
}
e.preventDefault();
};
const setupEventListeners = () => {
window.addEventListener('unhandledrejection', rejectionListener);
window.addEventListener('error', errorListener);
};
// Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
// the scope of this functionality.
if (typeof Zone !== 'undefined') {
Zone.root.run(setupEventListeners);
} else {
setupEventListeners();
}
inject(DestroyRef).onDestroy(() => {
window.removeEventListener('error', errorListener);
window.removeEventListener('unhandledrejection', rejectionListener);
});
},
},
);
/**
* Provides an environment initializer which forwards unhandled errors to the ErrorHandler.
*
* The listeners added are for the window's 'unhandledrejection' and 'error' events.
*
* @see [Global error listeners](best-practices/error-handling#global-error-listeners)
*
* @publicApi
*/
export function provideBrowserGlobalErrorListeners(): EnvironmentProviders {
return makeEnvironmentProviders([
provideEnvironmentInitializer(() => void inject(globalErrorListeners)),
]);
}