Using Angular 2: Implementing Router into myExceptionHandler

Within my app.module.ts, I've set up the following code:

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule
    ],
    providers: [
        {provide: ErrorHandler, useClass: MyExceptionHandler}
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}

Next, in my MyExceptionHandler:

import { Injectable } from "@angular/core"
import { Router } from "@angular/router"

@Injectable()
export class MyExceptionHandler {
    constructor (private _router: Router) {}

    handleError(error:any):void {
        ...
    }
}

Unfortunately, an error is popping up saying:

Error: Error: Provider parse errors

If I treat MyExceptionHandler as a normal provider, everything works smoothly. It seems like the ErrorHandler is being executed before the Router is fully instantiated. Any suggestions on how to fix this issue?

Answer №1

Here is the recommended code snippet from this Github thread:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
    private _router: Router;
    constructor(private _injector: Injector) {
        // Specify true to rethrow exceptions in Angular
        super(true);
    }

    handleError(error: any): void {
        // Delegate error handling to the default handler.
        super.handleError(error);

        if (!this._router) {
            this._router = this._injector.get(Router);
        }

        // Log the error and redirect to 500 page.
        this._router.navigate(['/errors/500']);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A different approach to showcasing components in SvelteKit based on the width of the screen

In my SvelteKit app, I'm using this code to retrieve the current window size and switch the displayed component when the width is small: <script> let size; </script> <svelte:window bind:innerwidth{size}/> <div> {#if size &g ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

Implementing onClick functionality to change background color with styled components

Is there a way to apply background color when a user clicks on any page in pagination using React styled components? I was able to achieve this with simple CSS by adding the class ".selected" which had a background-color of red, but now I need to use React ...

Encountered an issue while trying to install npm for an existing Angular 4 project

As a newcomer to angular 4, I attempted to import an existing project into my local machine. Using npm install to fetch the nodes_modules as per the package.json of the project, resulted in the following error: https://i.sstatic.net/pj52Q.png Here is the ...

Guide to accessing a menu through Long press or Right click in Angular2

I recently started experimenting with angular 2 and I am trying to figure out how to create a menu that opens with multiple options on both mobile and desktop devices. What I'm looking for is a way to trigger the opening of a menu when a long hold or ...

Enums are not recognized by TypeScript when used within an array

I have defined an enum as follows: export enum Roles { ADMIN, NONE; } An object is being used which utilizes this enum. The structure of the object is: export interface User { name: string; roles: Roles[]; } Upon fetching this object via a web r ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

Child routes in Angular tabs are failing to display in the currently active tab

Hey there! I'm currently working on navigating my Angular application using tabs, and I've run into a bit of an issue with the child routes. Specifically, when I switch to the second child route within the second tab, the status of the tab change ...

Expanding a component using the identical selector in Angular 2 / Angular-CLI

We are leveraging Angular to create a sleek component-based frontend for our primary application. Our various clients often request minor customizations to these core components. To maintain the integrity of our core code, we plan to store it in NPM packag ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Utilize multiple activated modules in Angular 2

Recently, I've been exploring the new features of Angular 2 final release, particularly the updated router functionality. An interesting example showcasing the router in action can be found at this link: http://plnkr.co/edit/mXSjnUtN7CM6ZqtOicE2?p=pr ...

What is the best way to send out Redux actions?

I'm in the process of creating a demo app with authorization, utilizing redux and typescript. Although the action "loginUser" in actions.tsx is functioning, the reducer is not executing as expected. Feel free to take a look at my code below: https:/ ...

Launching Nest.js application from Visual Studio Code

Currently experimenting with a new framework called which seems promising as it integrates TypeScript into Node, similar to Angular. I'm using the starter template from https://github.com/kamilmysliwiec/nest-typescript-starter. I can start it withou ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Display the date format based on the computer's settings using Angular 2

When I visited http://momentjs.com/docs/#/displaying/format/, I noticed the "Localized formats" options like L. I thought that these settings would change the date display from mm/dd/yyyy to dd/mm/yyyy based on the user's browser or computer locale s ...

Develop a flexible axios client

I have a basic axios client setup like this: import axios from "axios"; const httpClient = axios.create({ baseURL: "https://localhost:7254/test", }); httpClient.interceptors.request.use( (config) => config, (error) => Prom ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Tips on transforming a JavaScript function constructor into TypeScript

Transitioning from JavaScript to TypeScript has presented me with some challenges. One of the tasks I need to accomplish is converting a constructor function into its TypeScript equivalent. The original JavaScript function looks like this: export default ...