Home > database >  Checking the timeout error on the port with Angular 2 and rjxs
Checking the timeout error on the port with Angular 2 and rjxs

Time:03-19

I want to check if the request is timeout when I send a request to the port. I just want to print an error when the request is timeout.

myService.service.ts

checkStatus() : Observable<any> {
    return this.http.get<any>('http://127.0.0.1:3001'); // simple example
}

myComponent.ts

this.myService.checkStatus.subscribe(() => {}, 
  (err) => {
     // if the timeout error is print error
  }
}

I just want the error to be removed from the screen when the timeout error is fixed. if error 404 or a different error returns, I do not want the operation to be performed and printed to screen.

in short, it is as follows

  1. A request will be sent to the port and checked for a timeout error.
  2. If there is a timeout error, an error will be printed on the screen.(404 or different errors will not print, only timeout error)
  3. if there is a timeout error, it will be checked if the error persists, and if the error does not occur, the text on the screen will be removed.

CodePudding user response:

You can do something like this, to catch your error.

this.myService.checkStatus
  .pipe(
     catchError(error) => // do something with it)
   )
  .subscribe(yourResponse => // handle your response)

CodePudding user response:

Using retryWhen to check timeOut error with certain interval,and which is here a inner observable,and outer observable only to emit mesages for ui

myService.service.ts

  checkStatus() : Observable<any> {
    return Observable.create((observer) => {
      this.http
        .get<any>('http://127.0.0.1:3001')
        .pipe(
          retryWhen((err) => {
            return err.pipe(
              switchMap((err, i) => {
                
                // If it is a time out error,
                // then emit message to display
                // and set next retry attempt
                // by returning timer observable
               
                if(err.status === 504){
                   observer.next("timeout error!");
                   return timer(2000);
                } else{

                   // If it's not a timeout error
                   // then return null or anything you want
                   // On basis of what you can remove message 
                   // from ui

                   observer.next(null);
                }
                throwError(() => 'sorry!');
              })
            );
          }),
          catchError((err) => {
            return throwError(err);
          })
        )
        .subscribe(console.log);
    });
  }

myComponent.ts

this.myService.checkStatus.subscribe(
  (res) => {
     // if the timeout error is print error
  }, 
  (err) => {
    
  }
}
  • Related