Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Created December 3, 2024 08:13
Show Gist options
  • Save LayZeeDK/91067eec851f3a5d17184b64725b7c42 to your computer and use it in GitHub Desktop.
Save LayZeeDK/91067eec851f3a5d17184b64725b7c42 to your computer and use it in GitHub Desktop.
Angular ErrorHandler with plugins
@Injectable()
export class ErrorHandlerWithPlugins extends ErrorHandler {
readonly #plugins = inject(errorHandlerPluginToken, { optional: true }) ?? [];
override handleError(originalError: unknown): void {
super.handleError(originalError);
this.#plugins.forEach((plugin) => {
try {
plugin.handleError(originalError);
} catch (pluginError: unknown) {
setTimeout(() => this.#handlePluginError(plugin, pluginError), 0);
}
});
}
#handlePluginError(plugin: ErrorHandler, pluginError: unknown): void {
this.#plugins
.filter((otherPlugin) => otherPlugin !== plugin)
.forEach((otherPlugin) => {
try {
otherPlugin.handleError(pluginError);
} catch (_otherPluginError: unknown) {
// Ignore error from other plugin
} finally {
// Log to console
super.handleError(pluginError); // ❌ SyntaxError
}
});
}
}
@Injectable()
export class ErrorHandlerWithPlugins extends ErrorHandler {
readonly #plugins = inject(errorHandlerPluginToken, { optional: true }) ?? [];
override handleError(originalError: unknown): void {
super.handleError(originalError);
this.#plugins.forEach((plugin) => {
try {
plugin.handleError(originalError);
} catch (pluginError: unknown) {
setTimeout(() => this.#handlePluginError(plugin, pluginError), 0);
}
});
}
protected baseHandleError(error: unknown): void {
super.handleError(error); // ✅ Works
}
#handlePluginError(plugin: ErrorHandler, pluginError: unknown): void {
this.#plugins
.filter((otherPlugin) => otherPlugin !== plugin)
.forEach((otherPlugin) => {
try {
otherPlugin.handleError(pluginError);
} catch (_otherPluginError: unknown) {
// Ignore error from other plugin
} finally {
// Log to console
this.baseHandleError(pluginError);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment