Issues with error handling in Angular 7 causing unexpected behavior

Encountering issues with 422 error handling in my HTTP request. The error block is not executing as expected when using the catchError operator in the service. If no errors occur, the code functions properly. However, I need to show an error message on the page instead of just logging it to the console.

The following is the HTTP error response:

Only receiving the error message in the console:

https://i.sstatic.net/m1Qtt.png

My goal is to display the error message on the page. Below is my HTTP request:

 renderPlugin(id): Observable<any> {
 return this.http
      .get(`${environment.kbUrl}/${id}?_as_json=1&_nbp=1`, {
        responseType: "text",
        observe: "response"
      })
      .pipe(
        catchError((res: HttpErrorResponse) => {
          console.log(JSON.stringify(res));
          this.toastr.error("error", JSON.stringify(res));
          return throwError(JSON.stringify(res));
        })
      );
  }

Here is how I'm subscribing to it:

this.pluginsService.renderPlugin(this.currentId).subscribe(res =>{
    this.currentString = res.body;
    this.plugin = this.currentString.data.content;
    console.log(this.plugin);
      },
      err =>{
        this.plugin = err;
      });

Answer №1

It seems like there might be an interceptor in place to intercept the error. If you are looking to manage errors within the interceptor, one approach could be to handle them first before allowing them to propagate further.

Answer №2

To improve your code, consider eliminating the following section from your Http call:

  .pipe(
    catchError((res: HttpErrorResponse) => {
      console.log(JSON.stringify(res));
      this.toastr.error("error", JSON.stringify(res));
      return throwError(JSON.stringify(res));
    })
  )

Instead, handle errors within the error block of your subscribe method like this:

this.pluginsService.renderPlugin(this.currentId).subscribe(
    res => {
        this.currentString = res.body;
        this.plugin = this.currentString.data.content;
        console.log(this.plugin);
    },
    err => {
       // Handle the error here
       // such as displaying a toast with the error message received from the server
       this.plugin = err;
    }
);

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

Display the complete image once the loading process is finished on Angular 12

When retrieving image src via API from the server, I aim for the image to only be displayed once completely loaded. In the meantime, I would like a skeleton outline to be shown during the loading process (images are segmented into sections and the skeleton ...

The Autoplay feature in Swiper.js for (Ionic / Angular) is not activating

—— Concern —— Hello, I'm having trouble with getting the swiper to start autoplay as it should. After checking the swiper instance from the (swiper) event, here are the results I found: swiper.params.autoplay: {delay: 1000, enabled: true} s ...

Enhancing Forms with Redux and Styled Components

I'm currently working on developing a reusable component that involves using a redux-form <Field /> and styling it with styled-components within the component. The issue I'm facing is that none of the styles are being applied. Here is my ...

Extract objects from a nested array using a specific identifier

In order to obtain data from a nested array of objects using a specific ID, I am facing challenges. My goal is to retrieve this data so that I can utilize it in Angular Gridster 2. Although I have attempted using array.filter, I have struggled to achieve t ...

Guide to Validating Fields in Angular's Reactive Forms After Using patchValue

I am working on a form that consists of sub-forms using ControlValueAccessor profile-form.component.ts form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Valid ...

What is the process of extracting an observable from another observable using the pipe method?

Is there a more efficient way to convert an Observable of Observables into an array of Observables in my pipe method? Here is the scenario: // The type of "observables" is Observable<Observable<MyType>[]> const observables = this.http.get<M ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

The Material-UI TextField is placed in the Header section of the page

As I scroll down the page, I noticed that the TextField in the header area remains visible. This header is styled using CSS and includes a TextField from the material-ui library. This is my first time creating a header with CSS. Are there any specific cod ...

What is the best way to showcase an Angular component that has been initialized programmatically?

I currently have the following set up: Users Component HTML: <div class="users"> <ul class="users__list"> <li *ngFor="let user of users"></li> </ul> </div> Users Component TS: impo ...

Populate an Angular form using @Input to display data retrieved from a Firebase database through a service injection

I've encountered a challenge while working on an Ionic Angular project involving a form. The issue I'm facing is related to a component that serves as a form filled by an Input (Component). The problem seems to be that the form gets populated be ...

Unexpected behavior in hash-routing functionality of Angular application

My Angular7 app was functioning well in localhost, but when I moved it to a docker container, I encountered an issue. While I am able to access abc.xyz and navigate to abc.xyz/dashboard or abc.xyz/browseIdea from the homepage, attempting to directly visit ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

What is the best way to organize the snapshots folder in a React project?

Currently, I am working on a React UI project that I must build by myself. Given the small size of the project, I have decided to use TypeScript and adopt a Test-Driven Development (TDD) approach. During this process, I've familiarized myself with be ...

Is it possible to dynamically check values in TypeScript?

[Summary] I am looking to dynamically expand my type in TypeScript based on an initial set of values. I want to avoid managing separate arrays/types and instead extend all strings in my type with '_max'. type ExtendedValueTypes = 'money&apos ...

The process of invoking the AsyncThunk method within the Reducer method within the same Slice

Within my slice using reduxjs/toolkit, the state contains a ServiceRequest object as well as a ServiceRequest array. My objective is to dispatch a call to a reducer upon loading a component. This reducer will check if the ServiceRequest already exists in ...

Exploring the Method of Utilizing JSON Attribute in typeScript

How to access JSON attributes in TypeScript while working on an Angular Project? I'm currently in the process of building an Angular project and I need to know how to access JSON attributes within TypeScript. test:string; response:any; w ...

Include html into typescript using webpack

Attempting to include HTML content into a variable using TypeScript and webpack has been my challenge. This is the current setup: package.json: { "devDependencies": { "awesome-typescript-loader": "^3.2.3", "html-loader": "^0.5.1", "ts-load ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

Can this function be rewritten in a manner that does not involve returning undefined?

Using angular fire, I am fetching data from firestore based on the logged-in user. After ensuring that the user object has been retrieved, I have a command to monitor changes in the document. async fetchUserCards() { let _user: UserModel = await this.aut ...