Dealing with request errors in Angular with RxJS - catchError() isn't as effective as expected

Update Alert: Problem Solved. Solution Provided Below

In my service class, I have the following code snippet:

public getListById(id:string): Observable<any[]> {
        return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
            map(obj => obj),
            catchError(error => this.handleError(error))
        )
    }

handleError(error: any): Observable<any> {
        console.log(error)
        this.snackBar.open(
            "Server Error",
            "X"
        )
        return EMPTY;
    }

And in my component, here is the code snippet:

this.myService.getListById(id).subscribe(
    res => { doSomethingWith(res) },
    error => { 
        this.noRows = true
        console.log(error)
    },
    () => { this.loading = false }
)

Upon encountering a 500 error while calling GET on the Rest API address, I wanted to handle it effectively.

However, the catchError() method within the pipe() was failing to catch the error and only executing the

() => { this.loading = false }
part of the subscribe().

I am struggling with understanding why the RxJs module is not allowing me to easily manage request errors when dealing with backend operations.

Any insight or guidance on what may be impeding my ability to elegantly handle request errors would be greatly appreciated.

Thank you for your assistance.

Solution Discovered:

The root cause was traced back to an Error Interceptor implemented by a previous developer that was malfunctioning.

To resolve the issue, I removed the problematic ErrorInterceptor and created a new one. Additionally, I corrected the 'providers' property configuration in my app.module.ts, rectifying the erroneous reference to the ErrorInterceptor class.

Answer №1

It's a clear indication that the error has been successfully captured by the catchError method.

The function handleError sends back EMPTY, which indicates closing the stream without any data emission. This is why you are observing this.loading = false.

Try adding a debugger statement before console.log(error) and then check the variables using developer tools; there might be an issue with this.snackBar.open.

Answer №2

Although this may seem unconventional, consider modifying the approach in the following way:

return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
  catchError(err => {
    this.errorMessage = err;
    return throwError(err);
  })
);

public errorMessage = null;

Initialize the error message as null by default: this.errorMessage = null;

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

Filtering an RXJS BehaviorSubject: A step-by-step guide

Looking to apply filtering on data using a BehaviorSubject but encountering some issues: public accounts: BehaviorSubject<any> = new BehaviorSubject(this.list); this.accounts.pipe(filter((poiData: any) => { console.log(poiData) } ...

Obtaining a return value from a function in Angular

After just starting to work with Angular, I am attempting to extract a value from a button displayed in the HTML using a function. `<button class="btn" id="btn-gold" (click)="value(9)" name="mybutton" value="9">` 9 I have also inclu ...

What is the best way to securely store a JWT Token received from Cognito after logging in through the Cognito Hosted UI?

Our current architecture involves front end Angular and backend nodejs/express. This setup functions in the following order: User logs in to the site via Cognito Hosted UI Upon successful login, the user is redirected to our home page with a code sent in ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

Merging Dates Array transforms the date located at the final index of the array

I have created a function that takes a Date object and a count as arguments and returns an array of Date objects starting from the given 'date' for 'count' times. However, I encountered an issue while working on the next part of the cod ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...

Intellisense in VS Code is failing to work properly in a TypeScript project built with Next.js and using Jest and Cypress. However, despite this issue,

I'm in the process of setting up a brand new repository to kick off a fresh project using Next.js with TypeScript. I've integrated Jest and Cypress successfully, as all my tests are passing without any issues. However, my VSCode is still flagging ...

Access a designated webpage with precision by utilizing Routes in Angular

Is it possible to display a different component in Angular routing based on a condition in the Routing file? For example, if mineType is equal to "mino", can I navigate to another component instead of the one declared in the Routing? Should I use Child ro ...

To set up Ionic on your project, run the command `npm install

After setting up a new Ionic project, I included the Android platform using the command ionic cordova platform add android. This action added the following entry in the config.xml file: <engine name="android" spec="~6.1.2" /> Prior to this, I came ...

Where Should akitaConfig Be Placed in Angular Development?

Despite my attempt to place akitaConfig directly in the constructor of my app.component.ts file, I am encountering issues with it not properly configuring the data stores created afterwards. My goal is to set resettable to be universally true. Currently, t ...

Guide on automatically populating a value in an input field

My form includes a hook that automatically populates inputs based on the zip code entered by the user, filling in their address details seamlessly. Unfortunately, this auto-fill feature triggers a re-render of the component, causing the modal to open and ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

Troubleshooting Google Authorization Issue in Angular 17: How to Fix the Error TS2304: 'google' Not Found in Angular 17

I am encountering an issue while attempting to integrate Google Auth into my Angular(+Express) application using the Google Identity Services library. Despite following the instructions provided in the Google tutorial, I am facing the error: "[ERROR] TS230 ...

Contrast between utilizing form data versus base64 encoding for transmitting images to a .NET API

Currently tackling an angular 2 project where I need to transmit images along with data to a .NET Core API. How can this be accomplished effectively? Utilizing a cropper that produces base64 output. In previous requests, sending a single image as for ...

Securing Single Page Applications

Have you ever wondered how SPA ensure the security of their sites? With all the embedded scripts, it seems like anyone could access and analyze the code. Do you have any thoughts on this? Additionally, when connecting to other web services that require sp ...

The dropdown menus in Bootstrap are expanding outside the screen when opened

When I click on the dropdown in the Navbar on the right side, the menus open up far to the right and are not visible until I scroll horizontally. Here is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

Limiting JSDoc/TypeScript type to a specific array element

Utilizing TypeScript with JSDoc poses a challenge as I aim to restrict a variable to one of the known values stored in an array. I am aware that it can be achieved like so: /** @type {'one'|'two'|'three'} */ let v = 'fo ...