Dealing with Angular errors: How to handle a 404 page not found situation

I am retrieving data from a JSON file by making an HTTP request. Once I subscribe to the data, I read the JSON content. In this scenario, my goal is to verify whether the path is incorrect and if so, return a 404 error message.

getMapConfig(): Observable<MapReportConfigModel> {
    let mapConfigData = `assets/mapReportConfig1.json`;
    return this.httpClient.get<MapReportConfigModel>(mapConfigData);
}

Load map function

loadMap(): void {
    try {
      this.mapReportConfigModel
        .getMapConfig()
        .subscribe((configData) => {
          this.configData = configData;

          // Initialize map
          mapboxgl!.accessToken = this.configData.accessToken;
          this.map = new mapboxgl.Map({
            container: this.configData.container,
            center: [this.configData.centerLat, this.configData.centerLng],
          });
         
// Check if API key is incorrect.
          this.map.on("error", (response) => {
            this.showError(
              "500",
              "mapReport.err_no_map_reports",
              "mapReport.err_generating_map_report_message"
            ).subscribe(() => {
              this.router.navigateByUrl("/dashboard");
              return;
            });
          });
        })
        .add(() => {
          // Hide loading spinner
          this.loadingService.hide(processId);
        });
    } catch (error) {
      return null;
    }
  }

In case of a 404 error, I aim to handle it within the catch block.

Answer №1

Try utilizing the RxJS Observable error in addition to next.

this.mapReportConfigModel.getMapConfig()
    .subscribe({
      next: (data)=>console.log('data',data),
      error: (err)=>console.log('error',err),
      complete:()=>console.log('complete')
    });

You can also achieve similar functionality with this structure:

 .subscribe(
      (result) => {
        // Handle result
        console.log(result)
      },
      (error) => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

https://rxjs.dev/guide/observable

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

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Encountering a Problem with Angular 2 RC HTTP_PROVIDERS

I recently upgraded my Angular 2 application to the RC version. Everything was working smoothly until I included HTTP_PROVIDER and created a service.ts file. However, now I am encountering an error: (index):14 Error: SyntaxError: Unexpected token <( ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

What is the right way to import a module in TypeScript?

There is a module that I have declared like so: declare module conflicts { export interface Item {} export interface Item2 {} export interface Item3 {} } I attempted to import this module in a component using the following code: import * from ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...

Generate a commitment from the function

I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6. private InsertPersonInDB(p ...

The custom function is not compatible with any of the available overloads

I'm setting up an event listener that triggers a function to update the state when the event occurs. import React, {useState, useRef, useLayoutEffect} from 'react'; const [width, setWidthIn] = useState<number>(0) const ref = useRef< ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

Filtering multiple columns in Angular Material's mat-table

I am attempting to integrate a filter into my table. You can view the table with the filter in action on this live demo. However, I am facing an issue where the filters are not narrowing down the results as expected. For instance, when I apply the ID filt ...

Guide on showing a dropdown menu depending on the data in the current array index within a table

I am working with an object array that I want to display in a table. My goal is to have a dropdown select if the 'validvalues' field is not empty. How can I achieve this so that each row in the table has different options from the array? When &ap ...

Tips for creating a versatile function in TypeScript that accepts either a single value or an array of values for two parameters

I'm currently working on a task to develop a versatile function that accepts a parameter called hashMapName, another parameter called 'keys' which can be either a string or an array of strings, and a callback function that will return either ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Efficient configuration for pnpm monorepo with TypeScript, vite, and rollup

Struggling to set up a monorepo using pnpm workspaces with typescript, vite for frontends, and rollup for backend microservices. Here's the current project structure: package.json <== all dependencies reside here tsconfig ...

An issue has arisen with loading chunks in Ionic 5/Angular, possibly due to an un

I am currently working on enhancing the offline capabilities of my Ionic 5 app. To achieve this, I have implemented a strategy where data is stored in SQLite while the app is connected, and then retrieved from SQLite when offline instead of making HTTP req ...

encountering issues with configuring TypeScript LSP in NeoVim with the use of the lazy package manager

Encountered an error in nvim when opening a .ts file. Using mason, mason-lspconfig, and nvim-lspconfig for lsp setup. Lua language lsp is functioning properly, but facing errors with ts files as shown in the screenshot below: https://i.stack.imgur.com/gYM ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Operating on a MacOS platform, the combination of Visual Studio 2019 with the Typescript and Sass

Currently, I'm facing a challenge with compiling my TypeScript to Javascript and Scss to css in Visual Studio 2019 (MVC .Net Core). Every compiler I've tried seems to be failing. Is there anyone out there who knows the process for accomplishing t ...