npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ng-error-handlers

v1.3.0

Published

Angular allows developers to have only one `ErrorHandler` at a time which sometimes may be suboptimal if you already have an error handler like `Sentry` and want to add additional error handling. In such cases you would have to extend the existing `ErrorH

Downloads

116

Readme

ng-error-handlers

Angular allows developers to have only one ErrorHandler at a time which sometimes may be suboptimal if you already have an error handler like Sentry and want to add additional error handling. In such cases you would have to extend the existing ErrorHandler and override handleError, add some error handling and call super.handleError(error). This might be quite annoying especially wheh you want to use multiple error handlers alongside with existing ones. This library allows you to provide multiple error handlers (both class and function based) which will be executed one by one when an error occures.

Installation

npm i ng-error-handlers

Angular version compatibility

Compatible with v17 and v18

Basic setup

import {provideErrorHandlers} from 'ng-error-handlers';

// Standalone projects
bootstrapApplication(AppComponent, {
    providers: [
        provideErrorHandlers(),
    ]
})

// Module based projects
@NgModule({
    providers: [
        provideErrorHandlers(),
    ]
})
export class AppModule {}

By default provideErrorHandlers doesn't provide any error handler. So if you want to have at least basic ErrorHandler you can provide it via withClassHandlers.

Class based handlers

A class must implement ErrorHandler interface from @angular/core.

import {provideErrorHandlers, withClassHandlers} from 'ng-error-handlers';
import {ErrorHandler} from '@angular/core';

class MyCustomHandler implements ErrorHandler {
    handleError(error: any) {
        // do some stuff
    }
}

// Standalone projects
bootstrapApplication(AppComponent, {
    providers: [
        provideErrorHandlers(
            withClassHandlers(ErrorHandler, MyCustomHandler)
        ),
    ]
})

// Module based projects
@NgModule({
    providers: [
        provideErrorHandlers(
            withClassHandlers(ErrorHandler, MyCustomHandler)
        ),
    ]
})
export class AppModule {}

Function based handlers

It is possible to just use a function to handle an error. A function must satisfy ErrorHandlerFn type from ng-error-handlers.

import {provideErrorHandlers, withFuncHandlers, ErrorHandlerFn} from 'ng-error-handlers';

const customHandler: ErrorHandlerFn = (error: any) => {
    // do some stuff
}

// Standalone projects
bootstrapApplication(AppComponent, {
    providers: [
        provideErrorHandlers(
            withFuncHandlers(customHandler)
        ),
    ]
})

// Module based projects
@NgModule({
    providers: [
        provideErrorHandlers(
            withFuncHandlers(customHandler)
        ),
    ]
})
export class AppModule {}

Usage with both class and function based handlers

import {provideErrorHandlers, withFuncHandlers, withClassHandlers, ErrorHandlerFn} from 'ng-error-handlers';
import {ErrorHandler} from '@angular/core';

class MyCustomHandler implements ErrorHandler {
    handleError(error: any) {
        // do some stuff
    }
}

const customHandler: ErrorHandlerFn = (error: any) => {
    // do some stuff
}

// Standalone projects
bootstrapApplication(AppComponent, {
    providers: [
        provideErrorHandlers(
            withClassHandlers(ErrorHandler, MyCustomHandler),
            withFuncHandlers(customHandler)
        ),
    ]
})

// Module based projects
@NgModule({
    providers: [
        provideErrorHandlers(
            withClassHandlers(ErrorHandler, MyCustomHandler),
            withFuncHandlers(customHandler)
        ),
    ]
})
export class AppModule {}

Injection context

provideErrorHandlers returns EnvironmentProviders and thus must be provided either on application level or route level with the appropriate EnvironmentInjector. Hence it is possible to use DI in both class and function based error handlers.

import {ErrorHandler} from '@angular/core';
import {ErrorHandlerFn} from 'ng-error-handlers';

class MyCustomHandler implements ErrorHandler {
    private readonly analyticsService = inject(AnalyticsService);

    handleError(error: any) {
        this.analyticsService.log(error);
    }
}

const myCustomHandler: ErrorHandlerFn = (error: any) => {
    const analyticsService = inject(AnalyticsService);
    analyticsService.log(error);
}

Catching failed dynamic imports

Sometimes a new release gets deployed but users are still using an old build with old chunk hashes and haven't fetched the new build. In such situations if a user tries to open a lazy route, the attempt will fail with such error

TypeError: Failed to fetch dynamically imported module: https://example.com/chunk-4XF37HCG.js

There is a handy withDynamicImportHandler function to handle such sitatuions

import {provideErrorHandlers, withFuncHandlers} from 'ng-error-handlers';
import {withDynamicImportHandler} from 'ng-error-handlers/dynamic-import-handler';

provideErrorHandlers(
    withDynamicImportHandler(),
    // custom behaviour
    withDynamicImportHandler(failedImport => alert(failedImport)),
)

It takes one argument callback that will be executed once a dynamic import error occurs. If callback is not provided then the default behavior will be the current page reloading.

Sentry integration

In a nutshell Sentry just replaces ErrorHandler with its own class SentryErrorHandler which can be done just like this

import {provideErrorHandlers, withClassHandlers} from 'ng-error-handlers';
import {SentryErrorHandler, init} from '@sentry/angular';

init({
    // Sentry options
});

provideErrorHandlers(
    withClassHandlers(SentryErrorHandler),
)

To make things easier there is a function withSentry which creates a class handler under the hood and calls Sentry.init() via APP_INITIALIZER.

import {provideErrorHandlers, withClassHandlers} from 'ng-error-handlers';
import {withSentry} from 'ng-error-handlers/sentry-handler';
import {browserTracingIntegration, replayIntegration, TraceService} from '@sentry/angular';
import {Router} from '@angular/router';
import {APP_INITIALIZER} from '@angular/core';

providers: [
    provideErrorHandlers(
        withSentry({
            dsn: "https://my.dsn",
            integrations: [
                browserTracingIntegration(),
                replayIntegration(),
            ],
            // Performance Monitoring
            tracesSampleRate: 1.0, //  Capture 100% of the transactions
            // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
            tracePropagationTargets: [
                "localhost",
                /^https:\/\/yourserver\.io\/api/,
            ],
            // Session Replay
            replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
            replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
        }),
    ),
    // Provide additional things like TraceService
    {
        provide: TraceService,
        deps: [Router],
    },
    {
        provide: APP_INITIALIZER,
        useFactory: () => () => {},
        deps: [TraceService],
        multi: true,
    },
]