Navigate to Angular component based on error status code

When it comes to handling errors in my application, I have implemented a comprehensive approach consisting of four key components. Firstly, an http interceptor is used to handle server returned errors effectively. Secondly, I have a global error handler that extends the functionality of the default Angular error handler. Additionally, there is an error service in place to log errors for backend support purposes. Lastly, a Material dialog component is utilized to provide a user-friendly message in case of errors.

In certain scenarios, such as encountering a 404 error, I aim to capture the error status code and redirect to a specific component to enhance the end user experience. For instance, if the server responds with a 404 status code, the user should be redirected to a custom "not found" component without displaying an error dialog.

To achieve this, I have created an http interceptor that includes logic to detect the 404 status code and perform the necessary redirect. Here's a snippet of the interceptor implementation:

// Implementing the HttpErrorInterceptor class to manage HTTP errors
import { Injectable } from '@angular/core';
...
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(...) {}
  
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      retry(1),
      catchError((error: HttpErrorResponse) => {
        if (error.status === 404) {
          console.log('error.status: ', error.status);
          // Redirect to the desired component
        } else {
          // Handle other types of errors accordingly
        }
      })
    );
  }

  openDialog(data): void {...}
}

While the interceptor successfully handles the redirection based on the error status code, I encountered an issue where the global error handler is inadvertently triggered alongside the redirection process. The intention is to only redirect in case of a 404 error without invoking the global error handler.

For managing global errors, I've implemented a GlobalErrorHandler class that captures errors application-wide and logs them appropriately. Here's an excerpt from the Global Handler implementation:

// Implementation of the GlobalErrorHandler class to handle and log errors
import { ErrorHandler, Injectable, Injector } from '@angular/core';
...
@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private injector: Injector, public dialog: MatDialog) {}

  handleError(error: Error) {
    // Error handling logic
  }

  openDialog(data): void {...}
}

Is there a way to ensure that when a 404 error occurs, the redirection is executed without triggering the execution of the global error handler? Any insights or suggestions would be greatly appreciated.

Answer №1

Thanks to the guidance from Z.Bagley and the helpful link provided, I was able to successfully resolve the issue at hand. Upon further inspection, I discovered that the missing element in my code was the next.handle() call.

Below is the updated version of my interceptor code:

if (error.status === 404) { 
    const newRequest = request.clone();
    return next.handle(newRequest); 
} 

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

Why is the response from this HTTP request displaying array lengths instead of actual content?

I am currently working on a project involving fetching data asynchronously from an API. Everything seems to be working fine, except for when I attempt to add the correct answer to the incorrect answers array. Instead of displaying the content, only the len ...

Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner: app.controller('TestCtrl', function ($scope, safePostService) { $scope.count = safePostService.queue.length; $ ...

Utilize a special JavaScript function to submit a concealed PayPal form

Looking to integrate a call to PayPal within a JavaScript function. The goal is for the PayPal call to occur prior to running myStep1 and myStep2. Check out the function below: function() { // insert PayPal call here, before myStep1 and myStep2 ...

Creating an Observable Collection in Angular using AngularFire2 Firestore

I am currently using material 2 and attempting to develop data tables with pagination and sorting. In order to achieve this, I require my collections to be observable. However, I believe that I might be incorrectly populating or initializing the arrays in ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

A problem has occurred in Next.js where FileReader is not recognized and is causing a Reference

Exploring the latest features of Next.js 13 with the /app directory, I encountered an issue while using the FileReader in a basic client-side component that manages an input form. Here is a brief overview of the code: "use client"; import React, ...

Processing information from a JSON file and storing it in a database

I'm facing an issue with uploading a JSON file to my express app, reading data from the file and saving it as a new document in my MongoDB database. The documents are being saved but the fields are coming up as undefined for some reason. How can I res ...

Utilize the power of dual API integration in a single request (multi-scope capability)

While there may not be a definitive answer to this question, I want to ensure that my situation cannot be resolved in any way. The crux of my application (and consequently the issue) is that each user possesses their own unique database and does not have ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...

Opting for pre-selected default data within Material UI's select component

When utilizing the select component in Material UI, I am tasked with passing data as props to set a default selected value. The parent component provides the coursename prop, which can be accessed through this.props.coursename. I want this passed course to ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

Guide to Sending and Scheduling Notifications through HTML 5's Notification Web APIs

Is it possible to utilize Web APIs to Schedule Notifications and send them at specific times? I am working on a CMS application that allows users to schedule and send push notifications for their mobile apps. I am interested in implementing something sim ...

"Trouble arises when event listener fails to function following an append operation

Recently, I delved into the world of HTML/CSS and jQuery in an attempt to create a simple web game. Below is a snippet of my HTML code: function playGame() { var theLine = "<div id = \"line\">"; for (var i = 0; i < 9; ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

Issues with the functionality of the sliding menu in Angular are being encountered when trying to use $

Challenge I am facing an issue with a slider menu feature that I integrated into a mobile application for navigation purposes. The menu is functioning properly - it displays, allows flicking of the initial links, and can be closed by pushing the backdrop. ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

The TypeScript compiler remains silent when a declaration is missing

Encountered an unusual issue in my NodeJS project that I need help with. I suspect there is a simple solution hidden in tsconfig.json. Currently, I am working with TypeScript v1.7.3. The file test1.ts includes a variable declaration: // test1.ts let a = ...