How to navigate to a custom error page in Angular 2

I have set up a custom error handler and in that, I want to redirect to a custom error page displaying the message "sorry, an error occurred......".

To achieve this, I added a route in my app-routing.module.ts file as follows:

import { NgModule } from '@angular/core';
import { PreloadAllModules, Routes, RouterModule } from '@angular/router';

import { NoContentComponent } from './no-content/no-content.component'
import { CustomErrorComponent } from './customerror/customerror.component';

const routes: Routes = [
    { path: '',   redirectTo: '/home', pathMatch: 'full' },
    { path: 'resources',  loadChildren: 'app/educational-materials/educational-materials.module#EducationalMaterialsModule' },
    { path: 'administrative',  loadChildren: 'app/dsc/dsc.module#DSCModule' },
    { path: 'ask-a-question',  loadChildren: 'app/aaq/aaq.module#AAQModule' },
    { path: '**', pathMatch: 'full', component: NoContentComponent },
    { path: 'error', component: CustomErrorComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
    exports: [RouterModule],
    providers: []
})

export class AppRoutingModule { }

In my global exception handler implementation, I have included the following code:

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

@Injectable()

export class GlobalExceptionErrorHandler implements ErrorHandler {
    private router: Router;

    constructor(injector: Injector) {
        setTimeout(() => this.router = injector.get(Router));
    }

    handleError(error) {
        console.log('globalExceptionHandler | handleError...');

        this.router.navigate(['/error']);
    }
}

However, when I try to navigate to the error page using this.router.navigate(['/error']), it redirects to a 404 error page instead of my CustomErrorComponent page.

If I remove the front slash from the navigation command, nothing happens. How can I ensure that the CustomErrorComponent is called correctly?

Edit:

This is the CustomErrorComponent code:

import { OnInit } from '@angular/core';

export class CustomErrorComponent implements OnInit {
    constructor() { }

    ngOnInit() {
    }
}

And here is the HTML for the error page:

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h3>Sorry, an error occurred processing your request. The error has been logged.</h3>
        </div>
    </div>
</div>

Is it possible that the route is not configured in the correct place, causing the navigation issue?

Edit2: After noticing that the handleError function was being triggered multiple times, I enabled error logging and found an error stating "No component factory found for CustomErrorComponent." This led me to add entryComponents property to my CustomErrorComponent file:

import { OnInit, Component } from '@angular/core';

@Component({
    entryComponents: [CustomErrorComponent]
})

export class CustomErrorComponent implements OnInit {
    constructor() { }

    ngOnInit() {
        console.log('customErrorComponent | ngOnInit...');
    }
}

But now, I am encountering the error "Component CustomErrorComponent is not part of any NgModule or the module has not been imported into your module" whenever I try to load the app. Where should I register my component to resolve this issue?

Answer №1

The primary issue arises from the positioning of the variable routes within the file app-routing.module.ts. Currently, the entry for ** precedes that of error, causing the router to always navigate to **.

By reordering the entry ** to be the last one within the routes array, the entry for error becomes accessible.

Furthermore, it was observed that following the updates, the @Component({}) decorator in CustomErrorComponent had been removed.

To rectify this, let's restore the decorator and ensure that the CustomErrorComponent file contains the following code:

import { OnInit, Component } from '@angular/core';

@Component({
    selector: "customErrorComponent",
    templateUrl: './customerror.component.html'
})

export class CustomErrorComponent implements OnInit {
    constructor() { }

    ngOnInit() {
        console.log('customErrorComponent | ngOnInit...');
    }
}

Additionally, remember to include the CustomErrorComponent in the entryComponents section of your main module.

Simply add

entryComponents: [CustomErrorComponent]
to your main Module.

This adjustment successfully resolves the issue. For further details, interested readers can refer to the conversation thread associated with the question.

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

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Failed to deploy JEST test using THREE JS OrbitControls due to ENOENT error

I have successfully implemented a new feature that utilizes the Orbit Controls library. Everything is functioning properly, and I imported the Three.js module as per the documentation: import { OrbitControls } from 'three/examples/jsm/controls/OrbitC ...

The Ionic mobile application fails to show any content on the screen

After following a tutorial by Josh Moroney on "Building a Review app with Ionic 2, MongoDB, and Node", I created a basic ionic app. However, when I run the app using the `ionic serve` command, it loads in the browser without any errors but displays a compl ...

Angular asynchronous request does not yield any results

After executing ngOnChanges, the method _generateLocationFormForApproval is called, resulting in the output this.absoluteUri. Following this, _pageEventDealsForApprovalList is invoked. However, when trying to access the value of this.absoluteUri inside _pa ...

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

What are some best practices for implementing pagination using Angular Material?

While following a tutorial by Muhi Masri on how to implement an Editable Dynamic Table using Angular Material Paginator (the tutorial can be found here, highly recommended), I encountered an issue where the paginator was not working as expected. Despite fo ...

What are the steps to create a project using TypeScript and your neighborhood library?

As I work on developing my app that requires a library written in TypeScript and normally installed via npm, I find myself frequently needing to make edits to it. Ideally, I would like to be able to directly edit the library and see the changes reflected ...

Is it deemed as an anti-pattern to establish directives for styling?

Currently, I am in the midst of developing a specialized component UI library for a specific project I'm involved in. This library will consist of unique stylized components with elements that are reused throughout. As I work on this project, I find ...

What is the maximum UIRouter version that is supported with Angular 6?

Scenario: As my team and I near the completion of migrating our app from AngularJS to Angular 6, we are facing a dilemma. We are currently using UIRouter's implementation for angular-hybrid, and we are not ready to switch to Angular routing just yet. ...

Having trouble getting POST requests to work in Angular 8 for unknown reasons

Hey there! I'm currently experimenting with using POST requests to an API in Angular for the first time, but unfortunately it's not working as expected. I've checked out some other examples of code and everything seems fine. Here is a snipp ...

Angular fixes corrupted Excel files

My current project involves using Angular to call an API and retrieve a byte[] of an Excel file. However, I am facing issues with the file becoming corrupted when I convert the byte[] to a file using blob. Can anyone offer assistance with this problem? M ...

What is the proper way to implement Sequelize JOINs while using TypeScript?

Seeking guidance on how to properly JOIN two tables in Sequelize: const results = await MainModel.findAll({ include: [ JoinedModel ] }); Struggling with TypeScript's complaints when trying to access data from the joined table: const joinedField = r ...

Tips for confirming mat-datepicker entry with a defined format?

Currently utilizing mat-datepicker which allows users to manually input a date. Seeking a method to validate the date in the MM/DD/YYYY format: const dobRegex: RegExp = /((?:0[1-9])|(?:1[0-2]))\/((?:0[0-9])|(?:[1-2][0-9])|(?:3[0-1]))\/(\d{4 ...

Navigate to a different page using Angular2 routing

Looking for guidance on using redirect in the new Angular 2 router. Specifically interested in examples similar to 'redirectTo' from the beta version. Any demos on 'plnkr.co' would be greatly appreciated! ...

Error: Unable to assign value to property 12 because the object does not support extensibility

I'm facing an issue with my client application as I cannot figure out the error I am encountering. Despite successfully subscribing to a GraphQL subscription and receiving updates, I am struggling to update the TypeScript array named "models:ModelClas ...

The object created from winRef.nativeWindow.Razorpay is not a valid constructor

I am currently using Angular 4 for a project and I need to integrate razorpay into the project. While it works perfectly fine in the test and development environments, I encounter an error in a specific environment, the live environment. vendor.cdeb9a87 ...

Tips for concealing a Div in an HTML document with the help of Angular

I need a solution to hide a div that contains only titles, while the div with the actual content is located in a different section <div> <b>Delivery Info\</b> <div class="custom-control">Delivery ID: </div ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

Positioning the Datepicker Popup in Angular Material

https://i.sstatic.net/lD54U.png Can someone provide a solution for displaying the popup below the input? It is currently affecting the user interface. Any assistance would be greatly appreciated. ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...