Created
December 3, 2024 08:13
-
-
Save LayZeeDK/91067eec851f3a5d17184b64725b7c42 to your computer and use it in GitHub Desktop.
Angular ErrorHandler with plugins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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