How to capture and handle HTTP errors within a form using Angular 8 and RxJS

I am currently working on intercepting requests using the following code:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let tokenPromise = this.storage.get('token');

    return from(tokenPromise).pipe(mergeMap(token => {
      let data = {
        headers: request.headers.set('MyToken', token)
      };
      let newReq = request.clone(data);
      return next.handle(newReq);
    }));

}

In addition to intercepting requests, I would like to know how I can also intercept 404 errors. Can anyone provide guidance on this?

Answer №1

Keep in mind that when using HttpClient, it returns an Observable. Therefore, you can handle errors just like with any other observable by utilizing the catchError method.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let tokenPromise = this.storage.get('token');
    return from(tokenPromise).pipe(
       mergeMap(token => {...}),
       catchError((error: HttpErrorResponse) => {
          if (error.status === 404) {
             // implement some logic
          }
          return throwError(error);
       })
    );
}

Answer №2

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private auth: AuthenticationService, private notifier: NotificationService) {}

  intercept(req: HttpRequest<any>, nextHandler: HttpHandler): Observable<HttpEvent<any>> {
    return nextHandler.handle(req)
      .pipe(handleErrors((err) => {
        if (err.status === 404) {
          // handle error
        }
    }));
  }
}

Don't forget to include in your app.module.ts under providers:

{provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true}

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

Modify a attribute using event handlers from the main template

I've been experimenting with designing components using FASTElement. But I've hit a roadblock trying to pass a dynamic property from parent to child component. Here's a snippet of my design, featuring two FAST templates: childCompTemplate.t ...

The json-server-auth feature is failing to function properly upon initialization

I recently attempted to use json-server-auth by installing it via npm, but encountered a problem when trying to start it. The error message I received is as follows: json-server-auth : The term 'json-server-auth' is not recognized as the name ...

Tips for synchronizing arrays using the Angular Drag-Drop Component

My drag and drop component in HTML looks like this: <div class="example-container flex flex-col text-center h-fit min-h-[10rem] w-[15%] border-2 border-gray-100 rounded-md shadow-md" > <h2 class="text-xl font-semibo ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...

What is the reason behind not being able to perform a null check on an array entry in Typescript

I've got an array filled with objects that may be either null or a Gamepad: let devices: (Gamepad | null)[] = navigator.getGamepads() If the first item in the array happens to be a valid Gamepad, I need to perform a specific action: let device: Gam ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

A guide on how to retrieve an observer from localStorage or another observer in Angular2

Can anyone help me with my "loantype" service get() function: get() { return new Observable(observer => { let response; if ( localStorage.getItem('loantypes_are_valid') === '1' ) { response = JSON.parse(localStorage. ...

What is the best way to determine the appropriate version of angular/common needed to fulfill the dependencies?

After deploying my changes to the master branch, the pipeline encountered a failure. It seems that there is a version conflict for @angular/common required by different dependencies in the project. The main project requires @angular/common@"^16.0.0&qu ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

Guide on installing an Angular8 application on a personal computer in a secure manner

Exploring two intriguing queries that may appear theoretical. Despite scouring the internet, a definitive answer remains elusive. Query one: The aspiration is to craft an application in MEAN stack (Mongo, Angular8, NodeJS server) sans reliance on a centr ...

Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection. I have attemp ...

Importing ES Module is a requirement when making updates to Angular framework

During the process of upgrading from Angular 6 to 8, I encountered a frustrating issue. Every time I attempt to run 'ng serve' or 'ng build', I encounter the following error: I have tried various solutions such as adding "type":"module ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage &g ...

Implementing styles on the parent document through the child document

Currently, I am working on a chat widget application script and my goal is to apply styles to the parent document's body from the child document (the chat widget application). So far, I have attempted to access the parent document using the window ob ...

Together, we have a shared Yarn JS directory for both the client and server components,

The scenario: both the client and server share a folder named shared when we make changes to the shared folder in our development process, we need the corresponding references to update in both the client and server the server seems to w ...

Unable to establish a value for the input field

I need to verify if an object has a value without generating an error. If it does, I want to set it as the value of an input field. export class DialogServiceTabletAddRowComponent implements OnInit { service?: string; constructor(private _dialogRef: M ...

Using the double question mark operator in React JS and Typescript

The .NET framework includes the Null coalescing operator, which can be utilized in the following manner: string postal_code = address?.postal_code; Is it possible to achieve the same functionality in React JS? It seems that we can accomplish this using ...

Mastering the nesting of keys in Typescript.Unlock the secrets of

I encountered a situation where the following code snippet was causing an issue: class Transform<T> { constructor(private value: T) {} } class Test<T extends object> { constructor(private a: T) {} transform(): { [K in keyof T]: Transfo ...

Adjust the dimensions of the Angular Material checkbox component (mat-checkbox)

Is there a proper way to increase the size of the material checkbox? Trying to use transform to scale up the material checkbox, but unsure if this is the right method. CSS ::ng-deep .mat-checkbox .mat-checkbox-frame { transform: scale(2); } ::n ...

What is the best way to provide constructor arguments in Ionic 2 / Angular 2?

Currently in the process of upgrading my Ionic2.beta11 App to the latest release, Ionic2.rc0. Most aspects have been relatively smooth sailing, but I've hit a roadblock with the AoT compiler. Specifically, I'm encountering an issue with my AuthS ...